SQL Server Group By Query选择每个组的第一行

时间:2015-02-27 12:56:40

标签: sql sql-server

我正在尝试执行此查询。这就是我所拥有的。

我的表是:表

StudyID FacultyID Year    Access1   Access2    Access3
1          1       2014       4        8          5
1          2       2014       8        4          7
1          1       2013       5        4          4
2          3       2014       4        6          5
2          5       2013       5        8         10
2          4       2014       5        5          7
3          7       2013       9        4          7

我希望按StudyID和Year分组并获取每个字段Access1 Access2和Access3的最小值,并仅显示去年,我的意思是每个组的第一行。 这是结果。

StudyID  Year    Access1   Access2    Access3
1        2014       4        4          5
2        2014       4        5          5
3        2013       9        4          7

这是我的查询:

SELECT DISTINCT T.StudyID, T.Year, MIN(T.Access1), MIN(T.Access2), MIN(T.Access3)
FROM T
GROUP BY T.StudyID, T.Year
ORDER BY T.StudyID, T.Year DESC

我也试过这个。

 ;WITH MyQuery AS (     SELECT DISTINCT T.StudyID, T.Year, MIN(T.Access1), MIN(T.Access2), MIN(T.Access3),ROW_NUMBER() OVER (PARTITION BY T.StudyID, T.Year ORDER BY T.StudyID, T.Year DESC) AS rownumber
    FROM T  GROUP BY T.StudyID, T.Year      ORDER BY T.StudyID , T.Year DESC ) SELECT * FROM MyQuery WHERE rownumber = 1

任何成功,我知道我错过了什么......但不知道是什么? 在此先感谢!!!!

3 个答案:

答案 0 :(得分:7)

您可以GROUP BY StudyID, Year然后在外部查询中选择每个StudyID, Year组中的第一行:

SELECT StudyID, Year, minAccess1, minAccess2, minAccess3
FROM (
   SELECT StudyID, Year, min(Access1) minAccess1, min(Access2) minAccess2,
          min(Access3) minAccess3, 
          ROW_NUMBER() OVER (PARTITION BY StudyID ORDER BY Year DESC) AS rn 
   FROM mytable
   GROUP BY StudyID, Year ) t
WHERE t.rn = 1

ROW_NUMBER用于根据StudyID值为每个Year组分配订购号。具有最大Year值的行被指定为rn = 1

答案 1 :(得分:0)

试试这个:

SELECT DISTINCT T.StudyID, T.Year, MIN(T.Access1), MIN(T.Access2), MIN(T.Access3)
FROM myTable T
WHERE T.Year = (SELECT MAX(T2.Year) FROM myTable T2 WHERE T2.StudyID = T.StudyID)
GROUP BY T.StudyID

它在SQLite中提供了你想要的结果,但也许在SQL-Server中需要一些我不确定的别名。现在无法测试。

答案 2 :(得分:0)

这是你想要的答案

SELECT DISTINCT T.StudyID, T.Year, MIN(T.Access1) as Access1, MIN(T.Access2) as Access2, MIN(T.Access3) as Access3
FROM T T
WHERE T.Year = (SELECT MAX(T2.Year) FROM T T2 WHERE StudyID = T.StudyID)
GROUP BY T.StudyID, T.Year
Order by 1