Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

sql - Update a column based on ordered values from another table

I need to update a flag in a table called AccountBase when related table SoldItems has the same uniqueidentifier, but the hard part is, I need to find the latest product sold and compare its SellDatetime with the current time as well. When the latest product sold in 6 years I want set the flag to 1, otherwise 0.

There is 1:N connection between AccountBase and SoldItems, multiple items can be sold to one account, so I need to order it by SellDatetime in SoldItems.

Here is my attempt which is not setting it correctly, but the inner query in exists returns the proper value:

UPDATE acc 
   SET acc.SoldInLastSixYears = CASE WHEN DATEDIFF(DAY, hk.SellDatetime, GETDATE())/ 365.2425 >= 6 THEN 0
            ELSE 1
            END
FROM [AccountBase] acc INNER JOIN SoldItems hk ON acc.AccountId=hk.Owner
where EXISTS(select top(1) SellDatetime From SoldItems where 
SellDatetime is not null AND Owner is not null 
AND Owner=acc.AccountId   order by SellDatetime desc) 

When I try to use the inner query value there is an error I sql did not recognised 'hk':

UPDATE acc 
   SET acc.SoldInLastSixYears = CASE WHEN DATEDIFF(DAY, hk.SellDatetime, GETDATE())/ 365.2425 >= 6 THEN 0
            ELSE 1
            END
FROM [AccountBase] acc 
where EXISTS(select top(1) SellDatetime From SoldItems hk where 
SellDatetime is not null AND Owner is not null 
AND Owner=acc.AccountId   order by SellDatetime desc) 

Please someone help me, how it is should be done?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As far as I understood your problem, you want the latest record of the sellitem.

You can use correlated query with NOT EXISTS as follows:

UPDATE acc 
   SET acc.SoldInLastSixYears 
       = CASE WHEN DATEDIFF(DAY, hk.SellDatetime, GETDATE())/ 365.2425 >= 6 THEN 0
              ELSE 1
         END
FROM [AccountBase] acc INNER JOIN SoldItems hk ON acc.AccountId=hk.Owner
where NOT EXISTS(select 1 From SoldItems s where 
s.Owner=acc.AccountId and s.SellDatetime > hk.SellDatetime) 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.6k users

...