加入聚合

时间:2017-04-21 09:28:48

标签: sql-server join

SQL Server Interview Question

我在这样的面试中遇到了一个问题。输出将包含每个ID最高年龄和最高标记。

2 个答案:

答案 0 :(得分: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

答案 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

使用此查询,您将获得结果