I have multiple tables and each table has it's own last updated date. My requirement is to get the latest last date for a row.
For example:
I need to print the latest updated date among all the tables
I have written a query , but it is returning only one row
SELECT TOP 1
dates.Val,
dates.ID
FROM
(SELECT
A.ID, B.T_LAST_WRITE BDT, A.T_LAST_WRITE ADT
FROM
dbo.A, dbo.B
WHERE
A.ID = B.ID_) dt
UNPIVOT
(Val FOR L IN (ADT, BDT)) AS dates
ORDER BY
dates.Val DESC;
Can anyone please help?
I tried with the below query but it is returning only 1 record
SELECT TOP 1
dates.Val,
dates.ID
FROM
(SELECT
A.ID, B.T_LAST_WRITE BDT, A.T_LAST_WRITE ADT
FROM
dbo.A, dbo.B
WHERE
A.ID = B.ID_) dt
UNPIVOT
(Val FOR L IN (ADT, BDT)) AS dates
ORDER BY
dates.Val DESC;
2条答案
按热度按时间kupeojn61#
I think you wanted the latest date for each ID
kzmpq1sx2#
I agree with @Squirrel's answer. However, your posted code can also be made functional with the following changes:
GROUP BY dates.ID
SELECT MAX(dates.Val), dates.ID
(also dropping theTOP 1
)ID_
.Here is the updated SQL:
This db<>fiddle demonstrates both answers.