Get Latest Date from Multiple tables in Microsoft SQL Server

yizd12fk  于 2023-03-28  发布在  SQL Server
关注(0)|答案(2)|浏览(148)

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;
kupeojn6

kupeojn61#

I think you wanted the latest date for each ID

select ID, max(T_LAST_WRITE)
from
(
    select ID, T_LAST_WRITE from TableA
    union all
    select ID, T_LAST_WRITE from TableB
) c
group by ID
kzmpq1sx

kzmpq1sx2#

I agree with @Squirrel's answer. However, your posted code can also be made functional with the following changes:

  1. Add GROUP BY dates.ID
  2. Change the select to SELECT MAX(dates.Val), dates.ID (also dropping the TOP 1 )
  3. Fix the typo ID_ .

Here is the updated SQL:

SELECT
    MAX(dates.Val),
    dates.ID
FROM 
    (SELECT  
         A.ID, B.T_LAST_WRITE_DT BDT, A.T_LAST_WRITE_DT ADT
     FROM 
         dbo.A, dbo.B
     WHERE 
         A.ID = B.ID
    ) dt 
UNPIVOT 
    (Val FOR L IN (ADT, BDT)) AS dates
GROUP BY
    dates.ID
ORDER BY 
    dates.ID

This db<>fiddle demonstrates both answers.

相关问题