SQL - 识别连续的数据组

时间:2018-02-15 04:58:13

标签: sql sql-server group-by dense-rank

对于如下表所示,需要在D列中识别某个值的连续出现。我有一个C#脚本执行此操作,但如果有查询(或者基于temp的二三个)会很好表格)可以做到这一点。

C列:只能有0或1

SELECT   Column A,
         Column B,
         Column C
FROM     Table
ORDER BY Column A,
         Column B

样本表数据:

Column A,Column B,Column C
Employee 1,Value 1,0
Employee 1,Value 2,0
Employee 1,Value 3,0
Employee 1,Value 4,1
Employee 1,Value 5,1
Employee 1,Value 6,1
Employee 1,Value 7,0
Employee 1,Value 8,0
Employee 1,Value 9,1
Employee 1,Value 10,1
Employee 1,Value 11,1
Employee 1,Value 12,1

预期结果(编辑:C栏略作改动):

Column A, Start Value, End Value, Column C
Employee 1, Value 1, Value 1, 0
Employee 1, Value 2, Value 2, 0
Employee 1, Value 3, Value 3, 0
Employee 1, Value 4, Value 6, 3
Employee 1, Value 7, Value 7, 0
Employee 1, Value 8, Value 8, 0
Employee 1, Value 9, Value 12, 4

1 个答案:

答案 0 :(得分:1)

您可以使用行号的差异来执行此操作。运行子查询以查看其工作原理:

select a, c, min(b), max(b)
from (select t.*,
             row_number() over (partition by a order by b) as seqnum_a,
             row_number() over (partition by a, c order by b) as seqnum_ac
      from t
     ) t
group by a, c, (seqnum_a - seqnum_ac);