基于日期的增é‡å’Œå‡é‡è®¡æ•°

时间:2018-02-19 20:40:31

标签: sql postgresql

Name Start_date end_date
aaa  01/02/2017  05/03/2017
bbb  03/05/2017  07/07/2017
ccc  02/01/2017  10/09/2017

我想编写一个查询,用于计算æŸä¸ªæœˆ/年内数æ®åº“中存在的人数。

答案:

Jan 2017  1
Feb 2017  2
Mar 2017  3
Apr 2017  3
May 2017  2 (one person - aaa ,ended in May 2017)
Jun 2017  2
Jul 2017  1 (bbb ended in July 2017)

如何编写PSQL查询以获得所需的输出?

感谢。

1 个答案:

答案 0 :(得分:0)

首先,获å–最大和最å°æ—¥æœŸä»¥å£°æ˜Žæ—¥æœŸèŒƒå›´ã€‚

其次,使用etc选择范围内的所有月份。

第三,将æ¯ä¸ªæ—¥æœŸçš„记录数加起æ¥ã€‚

åƒï¼š

declare @date date 
declare @toDate date 


select @date = min(Start_date),
       @toDate = max(end_date)
from table_name

;With dt As
 (
 Select @date As [TheDate]
 Union All
 Select DateAdd(month, 1, TheDate) From dt Where [TheDate] < @toDate
 ) 

 select month(dt.TheDate),
        year(dt.TheDate),
        sum(case when table_name.Name is not null then 1 else 0 end)
 from dt
 left join table_name   
    on table_name.Start_date >= dt.TheDate
    and table_name.end_date < dateadd(day,-1,dateAdd(month,1,dt.TheDate))