sql组只能按顺序排列

前端之家收集整理的这篇文章主要介绍了sql组只能按顺序排列前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
说我有下表:
MyTable
---------
| 1 | A |
| 2 | A |
| 3 | A |
| 4 | B |
| 5 | B |
| 6 | B |
| 7 | A |
| 8 | A |
---------

我需要SQL查询输出以下内容

---------
| 3 | A |
| 3 | B |
| 2 | A |
---------

基本上我正在做一个组,但是只是为了排列在一起的行.有任何想法吗?

请注意,数据库sql Server 2008上.有一个关于这个主题的帖子,但是它使用oracle的lag()函数.

解决方法

这被称为“岛屿”问题.使用Itzik Ben Gan的方法
;WITH YourTable AS
(
SELECT 1 AS N,'A' AS C UNION ALL
SELECT 2 AS N,'A' AS C UNION ALL
SELECT 3 AS N,'A' AS C UNION ALL
SELECT 4 AS N,'B' AS C UNION ALL
SELECT 5 AS N,'B' AS C UNION ALL
SELECT 6 AS N,'B' AS C UNION ALL
SELECT 7 AS N,'A' AS C UNION ALL
SELECT 8 AS N,'A' AS C
),T
     AS (SELECT N,C,DENSE_RANK() OVER (ORDER BY N) - 
                DENSE_RANK() OVER (PARTITION BY C ORDER BY N) AS Grp
         FROM   YourTable)
SELECT COUNT(*),C
FROM   T
GROUP  BY C,Grp 
ORDER BY MIN(N)
原文链接:https://www.f2er.com/mssql/81426.html

猜你在找的MsSQL相关文章