A
A
Andrew2016-08-23 00:05:49
SQL
Andrew, 2016-08-23 00:05:49

How to make Update taking a value from a table sorted in reverse order?

Let's say there is a query like this:
update Table1
set Table1.F1= Table2.F2
from Table2
where Table1.F3= Table2.F4
The problem is that for each record, set occurs at the first match of F3 and F4, but I need to find the last match . I would write like this (but alas, such a query is not valid):
update Table1
set Table1.F1= Table2.F2
from (select * from Table2 order by Id desc) Table2
where Table1.F3= Table2.F4
How to write a query correctly?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Ananiev, 2016-08-23
@SaNNy32

Something like this

update Table1
set Table1.F1= Table2.F2
where Table1.F3=(select top 1 F4 from Table2 order by Id desc )

E
Edward, 2016-08-23
@edb

update Table1
set F1 = (SELECT TOP 1 (F2) FROM Table2 T2 WHERE T1.F3 = T2.F4 order by Id desc)
from Table1 t1

or with grouping, since the first value in the list, sorted in descending order, is the maximum
update Table1
set F1 = (SELECT MAX(F2) FROM Table2 T2 WHERE T1.F3 = T2.F4 GROUP BY F2)
from Table1 t1

it should be taken into account that if there is no suitable data in Table2, then it will be updated with NULL.

E
electwc, 2020-10-15
@electwc

You can first increase all values ​​by 1,000,000, and then decrease everything by 999,996, then there will be no duplicates

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question