0

I have a situation... i have these columns - table X

 Product   Number  LastEditDate    GUID
 A         0       14.12.16        A1
 A         0       10.12.16        A2
 B         0       10.12.16        A3
 B         0       13.12.16        A4
 C         0       13.12.16        A5
 C         0       14.12.16        A6

Now, i need to put Number 1 to all products where the Date is the Max. I was using this query:

update X set Number=0;
update X set Number=1 where LastEditDate in (select Max(LastEditDate) from X Group by Product);

So this will give me something like this:

Product    Number    LastEditDate
A          1         14.12.16
A          0         10.12.16
B          0         10.12.16
B          1         13.12.16
C          0         13.12.16
C          1         14.12.16

But, with my query, i have: 1;0;0;1;1;1; because 13.12.16 will be in that "select Max(LastEditDate) from X). How to make like that, to have results: 1;0;0;1;0;1;???

Please help!

5
  • Sorry, there should be a "Group by Product"...i missed it... Commented Dec 14, 2016 at 14:12
  • Edit your question instead of use a comment. Commented Dec 14, 2016 at 14:37
  • Is there any unique ID for each row in this table; Commented Dec 14, 2016 at 14:38
  • Yes, there is a GUID Commented Dec 14, 2016 at 15:06
  • Could you add it to your table example? Commented Dec 14, 2016 at 15:07

2 Answers 2

1

You should look for the pair (product, lasteditdate):

update x 
set number = 1 
where (product, lasteditdate) in (
    select product, max(lasteditdate) 
    from x 
    group by product);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, i think this should work. I just don't understand why i didn't this before? :) Thank you
0

You can check it here: http://rextester.com/YVLK16496

with t1 as (
    select Product, Max(LastEditDate) as MaxDate from t group by Product
)
update t
set Number=1
from t1
where t.Product = t1.Product and t.LastEditDate = t1.MaxDate;

1 Comment

This also could work for me but i will try the "klin" answer. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.