sql db2 group每年的第一天

时间:2016-03-18 11:07:07

标签: sql db2

我有以下内容:

id        date_start       date_end
-----     ----------       --------
1a3       2001-12-12       2002-12-12
23b       2005-01-24       2008-11-02
11ad      2012-01-15       2014-13-09
19d       2015-01-23       2016-02-04

我希望得到每个人的计数,其中日期范围包括每年的第一天。

例如我可以这样做:

select count(distinct id) from table
where '2001-01-01' between date_start and date_end

但是我希望从2000年到2015年生成所有年份的计数。我想避免手动操作:

select count(distinct id) from table
where '2001-01-01' between date_start and date_end

select count(distinct id) from table
where '2002-01-01' between date_start and date_end

select count(distinct id) from table
where '2003-01-01' between date_start and date_end

我只是难以将group by子句可视化。如果我只有一年的话,我可以这样做:

select count(distinct id), year from table
group by year

但是我不能将where '2001-01-01' between date_start and date_end放入这个组子句中。

任何人都可以帮忙吗?

谢谢!

3 个答案:

答案 0 :(得分:1)

您可以使用left join。这是一种方法:

select y.yyyy, count(distinct t.id)
from ((select '2001-01-01' as yyyy from sys.sysdummy) union all
      (select '2002-01-01' as yyyy from sys.sysdummy) union all
      (select '2003-01-01' as yyyy from sys.sysdummy)
     ) y left join
     table t
     on y.yyyy between date_start and date_end
group by y.yyyy
order by y.yyyy;

答案 1 :(得分:1)

嗯,你只需检查并计算date_start的年份是否与date_end的年份不同。

select count(*) 
  from table
 where year(date_start) < year(date_end)

答案 2 :(得分:0)

我希望你不介意我回答我自己的问题。使用Michael的逻辑,我能够将它与虚拟表结合起来 - 这是Gordon回答的一个想法。这就是我所做的:

with dummy(yr) as (
    select 2000 from SYSIBM.SYSDUMMY1
    union all
    select yr + 1 from dummy where yr < 2015
)

select d.yr, count(distinct t.id) 
from table t, dummy d
where d.yr between year(t.date_start) + 1 and year(t.date_end)
group by d.yr
order by d.yr

正如我所说,我希望社区不介意我把两个海报的部分答案都拿到我想要的解决方案。我不想要硬编码,我认为我发布的答案在使用简单的日期算术逻辑时满足了这一点。

相关问题