SQL:如何有效地找到具有连接的最小集合中的最小值

时间:2013-07-16 11:13:50

标签: sql-server join group-by

我想找到一所学校最小班的最年长的人

我有一张这样的表

School  Class    DOB         Stu_ID 
1 1 2000-10-05 S007 1 1 2001-08-03 S006 1 2 2000-10-05 S005 1 2 2001-08-03 S004 2 3 2000-10-05 S003 2 4 2001-08-03 S002 2 4 2000-10-05 S001 2 5 2001-08-03 S009

我需要将结果表格作为

School  Class    DOB         Stu_ID 
1 1 2000-08-03 S006 2 3 2000-10-05 S003

,即每所学校最小班的最年长的人。

3 个答案:

答案 0 :(得分:1)

SELECT
    School, Class, DOB, Stu_ID
FROM
    (
    SELECT
        School, Class, DOB, Stu_ID,
        DENSE_RANK() OVER (PARTITION BY School ORDER BY Class, DOB) AS rn
    FROM
        MyTable
    ) X
WHERE X.rn = 1

每个学校重置(PARTITION BY)并从最低等级开始计算,然后从最早的DOB开始计算。

DENSE_RANK允许学生分享生日

答案 1 :(得分:0)

您可以使用排名功能:

WITH CTE AS(
    SELECT School, Class, DOB, Stu_ID,
        RN = ROW_NUMBER() OVER (PARTITION BY School ORDER BY Class ASC)
    FROM dbo.Schools
)
SELECT School, Class, DOB, Stu_ID
FROM CTE WHERE RN = 1

Demo

答案 2 :(得分:0)

最好的方法是使用窗口函数来计算中间变量:

select School, Class, DOB, Stu_ID 
from (select t.*,
             dense_rank(ClassCnt) over (partition by school) as ClassSizeRank
      from (select t.*,
                   count(*) over (partition by school, class) as ClassCnt,
                   row_number over (partition by school, class order by dob) as AgeSegnum
            from t
           ) t
     ) t
where ageseqnum = 1 and ClassSizeRank = 1;

我不建议在这种类型的查询中使用连接。如果是家庭作业/班级,你应该在问题中指明。