DECLARE @Table TABLE
(
Col_status VARCHAR(5),
Col_Location VARCHAR(5),
Col_NUM INT
)
INSERT INTO @Table (Col_status, Col_Location, Col_NUM)
VALUES ('ON', 'AAA', 1), ('ON', 'AAA', 2),
('OFF', 'AAA', 3), ('ON', 'BBB', 4),
('ON', 'BBB', 5), ('ON', 'CCC', 6), ('ON', 'BBB', 7),
('OFF', 'AAA', 9), ('OFF', 'AAA', 10);
SELECT *
FROM @Table
输出:
Col_status Col_Location Col_NUM
---------- ------------ -------
ON AAA 1
ON AAA 2
OFF AAA 3
ON BBB 4
ON BBB 5
ON CCC 6
ON BBB 7
OFF AAA 9
OFF AAA 10
但我期待以下答案;我大部分时间都花在了这上面。
- 按第一列和第二列分组,但应根据第三列值的顺序进行拆分
输出应该是这样的:
Col_status Col_Location Min(Col_NUM) count(Col_NUM)
---------- ------------- ------------- --------------
ON AAA 1 2
OFF AAA 3 1
ON BBB 4 2
ON CCC 6 1
ON BBB 7 1
OFF AAA 9 2
谢谢和问候,凯瑟尔·M
最佳答案
这是一个孤岛和间隙问题。可以这样解决:
select t.Col_status,t.Col_Location, min(t.col_num), count(*)
from
(
select t.*, row_number() over (partition by Col_status,Col_Location order by Col_NUM) group_rn
from @Table t
) t
group by t.Col_status,t.Col_Location, t.col_num - t.group_rn
基本思想在t.col_num - t.group_rn
中,其中相同序列中的行(具有连续的id
)具有相同的差异结果。因此,t.col_num - t.group_rn
允许您隔离这些序列并正确进行分组。
关于sql - 如何在 SQL Server 中使用以下方法对数据进行 GROUP BY?缺口和岛屿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47134969/