Sql查询计算最近一年的连续总年数

Sql query to Count Total Consecutive Years from latest year(Sql查询计算最近一年的连续总年数)
本文介绍了Sql查询计算最近一年的连续总年数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个临时表:

 CREATE TABLE Temp 
( 
  [ID]  [int],
  [Year]  [INT],
 )
**ID    Year**
1 2016
1   2016
1   2015
1   2012
1   2011
1   2010
2   2016
2   2015
2   2014
2   2012
2   2011
2   2010
2   2009
3   2016
3   2015
3   2004
3   1999
4   2016
4   2015
4   2014
4   2010
5   2016
5   2014
5   2013

我想计算从最近一年开始的连续年份总数.结果应如下所示:

I want to calculate the total consecutive years starting from the most recent Year. Result should look like this:

ID  Total Consecutive Yrs
1   2
2   3
3   2
4   3
5   1

推荐答案

select ID,
   -- returns a sequence without gaps for consecutive years
   first_value(year) over (partition by ID order by year desc) - year +1 as x, 
   -- returns a sequence without gaps
   row_number() over (partition by ID order by year desc) as rn
from Temp

例如对于 ID=1:

1   2016    1   1
1   2015    2   2
1   2012    5   3
1   2011    6   4
1   2010    7   5

只要没有间隙,两个序列的增加都是一样的.

As long as there's no gap, both sequences increase the same.

现在检查相等的序列并计算行数:

Now check for equal sequences and count the rows:

with cte as 
 (
   select ID,
      -- returns a sequence without gaps for consecutive years
      first_value(year) over (partition by ID order by year desc) - year + 1 as x, 
      -- returns a sequence without gaps
      row_number() over (partition by ID order by year desc) as rn
   from Temp

 ) 
select ID, count(*)
from cte
where x = rn  -- no gap
group by ID

根据您的零年评论:

with cte as 
 (
   select ID, year,
      -- returns a sequence without gaps for consecutive years
      first_value(year) over (partition by ID order by year desc) - year + 1 as x, 
      -- returns a sequence without gaps
      row_number() over (partition by ID order by year desc) as rn
   from Temp

 ) 
select ID, 
   -- remove the year zero from counting
   sum(case when year <> 0 then 1 else 0 end)
from cte
where x = rn
group by ID

这篇关于Sql查询计算最近一年的连续总年数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Query with t(n) and multiple cross joins(使用 t(n) 和多个交叉连接进行查询)
Unpacking a binary string with TSQL(使用 TSQL 解包二进制字符串)
Max rows in SQL table where PK is INT 32 when seed starts at max negative value?(当种子以最大负值开始时,SQL 表中的最大行数其中 PK 为 INT 32?)
Inner Join and Group By in SQL with out an aggregate function.(SQL 中的内部连接和分组依据,没有聚合函数.)
Add a default constraint to an existing field with values(向具有值的现有字段添加默认约束)
SQL remove from running total(SQL 从运行总数中删除)