给定开始日期和结束日期的actvie事件分组(SQL Server)

时间:2018-08-02 14:57:23

标签: sql sql-server group-by

我面临一个挑战,那就是我有一个带有事件开始和结束日期的表:

select u.*
from uniques u
where not exists (select 1 from uniques u1 where u1.number = u.number and u1.desc <> u.desc);

我希望有一个表作为一个月中活动事件的分组依据:

Event Start       End
A     01Jan2018   01Mar2018
B     01Feb2018   01Apr2018

谁能想到使该请求可行的SQL语句?

THX 拉兹鲁(Lazloo)

3 个答案:

答案 0 :(得分:1)

一种方法会生成日期,然后使用相关子查询或apply进行计算:

with dates as (
      select cast('2018-01-01' as date) as dte
      union all
      select dateadd(month, 1, dte)
      from dates
      where dte < '2018-04-01'
     )
select d.dte,
       (select count(*)
        from t
        where t.start <= d.dte and t.end >= d.dte
       ) as num_active
from dates d;

答案 1 :(得分:0)

您需要apply和递归cte来生成开始事件日期:

with tt1 as (
     select event, cast(start as date) start, cast([end] as date) [end]
     from table
     union all
     select event, dateadd(month, 1, start), [end]
     from tt1
     where start < [end]
)

select year(tt.dt), month(tt.dt), tt1.cnt
from table t cross apply
     ( values (start), ([end]) 
     ) tt (dt) outer apply
     ( select count(*) cnt
       from tt1
       where year(tt1.start) = year(tt.dt) and
             month(tt1.start) = month(tt.dt)
     ) tt1;

答案 2 :(得分:0)

尝试一下:

declare @tbl table([Event] char(1), [Start] date  ,    [End] date);
insert into @tbl Values
('A'  ,   '01Jan2018',   '01Mar2018'),
('B'  ,   '01Feb2018',   '01Apr2018');
declare @start date,
        @end date;
select @start = min([Start]), @end = max([End]) from @tbl;

with cte as(
    select @start dt from @tbl
    union all
    select dateadd(month, 1, dt) from cte
    where  dateadd(month, 1, dt) <= @end
)

select datepart(month, c.dt), datepart(year, c.dt), count(distinct [Event]) from cte c
left join @tbl t on c.dt between t.Start and t.[End]
group by datepart(month, c.dt), datepart(year, c.dt)