在SQL中计算连续的重复值

时间:2014-12-02 14:49:30

标签: sql sql-server common-table-expression

我有一张像这样的桌子

ID     OrdID     Value
1      1          0     
2      2          0
3      1          1
4      2          1
5      1          1
6      2          0
7      1          0
8      2          0
9      2          1
10     1          0
11     2          0

我想得到值为0的连续值的计数。使用上面的例子,结果将是3(第6,7和8行)。我正在使用sql server 2008 r2。

2 个答案:

答案 0 :(得分:5)

我将假设id是唯一且不断增加的。您可以使用不同的行号来获取连续值的计数。以下计算所有序列:

select grp, value, min(id), max(id), count(*) as cnt
from (select t.*,
             (row_number() over (order by id) - row_number() over (partition by value order by id)
             ) as grp
      from table t
     ) t
group by grp, value;

如果你想要最长的0s序列:

select top 1 grp, value, min(id), max(id), count(*) as cnt
from (select t.*,
             (row_number() over (order by id) - row_number() over (partition by value order by id)
             ) as grp
      from table t
     ) t
group by grp, value
having value = 0
order by count(*) desc

答案 1 :(得分:3)

使用not exists查找连续0的查询

select top 1 min(t2.id), max(t2.id), count(*)
from mytable t
join mytable t2 on t2.id <= t.id
where not exists (
    select 1 from mytable t3
    where t3.id between t2.id and t.id
    and t3.value <> 0
)
group by t.id
order by count(*) desc 

http://sqlfiddle.com/#!3/52989/3