首页 / SQL Server / 正文

SQL Server 使用ROW_NUMBER和GROUP BY分组查询每组的第一条和最后一条数据记录

9357 发布于: 2015-12-14 读完约需5分钟
microsoft-sqlserver 假如我们有个分组查询的需求,要求按照指定字段进行分组并同时查询出分组字段的第一条和最后记录,大致数据如下: UNION查询1:
SELECT 1 AS ID, 110  AS TRAIN_ID
UNION
SELECT 2 AS ID, 111  AS TRAIN_ID
UNION
SELECT 3 AS ID, 112  AS TRAIN_ID
UNION查询2:
SELECT 110  AS TRAIN_ID , 1 AS ID,11111 NUM
UNION
SELECT 110  AS TRAIN_ID,2 AS ID,22222 NUM
UNION
SELECT 110  AS TRAIN_ID,3 AS ID,33333 NUM
UNION
SELECT 111  AS TRAIN_ID,1 AS ID,44444 NUM
UNION
SELECT 111  AS TRAIN_ID,2 AS ID,55555 NUM
UNION
SELECT 112  AS TRAIN_ID,1 AS ID,66666 NUM
要求查询的结果如下:
TRAIN_ID    FIRST       LAST
----------- ----------- -----------
110         11111       33333
111         44444       55555
112         66666       66666
你这时想的处理方式是怎样的呢?本文在这里也分享一下其中一种实现方式,供参考,实现代码如下:
WITH T1 AS(
	SELECT 1 AS ID, 110  AS TRAIN_ID
	UNION
	SELECT 2 AS ID, 111  AS TRAIN_ID
	UNION
	SELECT 3 AS ID, 112  AS TRAIN_ID
),
T2 AS(
	SELECT *,
		ROW_NUMBER() OVER (PARTITION BY TRAIN_ID ORDER BY NUM) AS RN1,
		ROW_NUMBER() OVER (PARTITION BY TRAIN_ID ORDER BY NUM DESC) AS RN2
		FROM (
			SELECT 110  AS TRAIN_ID , 1 AS ID,11111 NUM
			UNION
			SELECT 110  AS TRAIN_ID,2 AS ID,22222 NUM
			UNION
			SELECT 110  AS TRAIN_ID,3 AS ID,33333 NUM
			UNION
			SELECT 111  AS TRAIN_ID,1 AS ID,44444 NUM
			UNION
			SELECT 111  AS TRAIN_ID,2 AS ID,55555 NUM
			UNION
			SELECT 112  AS TRAIN_ID,1 AS ID,66666 NUM
		) AS T
)
SELECT T1.TRAIN_ID,
	MAX(CASE WHEN RN1 = 1 THEN NUM END) AS [FIRST],
	MAX(CASE WHEN RN2 = 1 THEN NUM END) AS [LAST] 
	FROM T1
	LEFT JOIN T2 ON T1.TRAIN_ID=T2.TRAIN_ID 
GROUP BY T1.TRAIN_ID
 

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: [C#/.NET]关于Web Api Put/Delete请求出现405错误的解决方案

下一篇: .NET WEB程序员需要掌握的技能[转]

本文永久链接码友网 » SQL Server 使用ROW_NUMBER和GROUP BY分组查询每组的第一条和最后一条数据记录

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册