Sqlserver
 sql >> Datenbank >  >> RDS >> Sqlserver

Wie kann ich das maximale Datum (pro Primärschlüssel) und die Differenz zu dem aus einer anderen Tabelle ermitteln?

WITH recorddates
AS
(
    SELECT  PKEY, REFNo, DATE,
            ROW_NUMBER() OVER (PARTITION BY RefNO
                                ORDER BY DATE DESC) rn
    FROM    table2
)
SELECT  a.PKEY, 
        datediff(day,a.DATE,b.date) 
FROM    table1 a
        INNER JOIN recorddates b
            ON a.PKey = b.RefNo
WHERE   b.rn = 1