2017-04-21 84 views
0

SQL Server Interview Question加入集合

我在面試中遇到了這樣的問題。輸出將包含具有最高標記的每個ID最高年齡。

+0

應該是什麼結果。如果像2 30 200 2 28 300個數據? –

回答

1

使用ROW_NUMBER()PARTITION BY如下,讓您的輸出

;WITH T AS 
(
    SELECT 
     ID, 
     Age, 
     Marks, 
     ROW_NUMBER() OVER(PARTITION BY ID ORDER BY Age DESC,MArks DESC) AS PartNo 
    FROM @tbl1 
) 
SELECT 
    T.ID, 
    T2.Name, 
    T.Age, 
    T.Marks 
FROM T 
LEFT JOIN @tbl2 T2 ON T.ID=T2.ID 
WHERE PartNo=1 
0
SELECT A.ID,A.Name,MA.MaxAge Age,MM.MaxMarks Marks FROM tbl2 A 
LEFT JOIN (SELECT Id, Max(Age)MaxAge FROM tbl1 GROUP BY ID) MA ON MA.ID = a.ID 
LEFT JOIN (SELECT Id, Max(Marks)MaxMarks FROM tbl1 GROUP BY ID) MM ON MM.ID = a.ID 

使用此查詢,你會得到你的結果