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

时间:2023-02-06
本文介绍了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查询计算最近一年的连续总年数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:“NVARCHAR"附近的语法不正确 下一篇:如何获得 T SQL 中 2 次之间的微小差异?

相关文章

最新文章