需要查询有些复杂的聚合

时间:2018-01-11 19:10:12

标签: sql sql-server

我还没有找到解决方法的方法(以优雅的方式),所以我想请求您帮助计算特定月份的平均工作时间。

declare @person table (pers_id int, [from] date, [to] date, hrs decimal(4, 2));
insert into @person values (72, '2017-09-01', '2017-11-13', 20);
insert into @person values (72, '2017-11-14', null, 35);

declare @months table (ym date);
insert into @months values ('2017-09-01');
insert into @months values ('2017-10-01');
insert into @months values ('2017-11-01');
insert into @months values ('2017-12-01');

/* so I need a query whouch would output average week-hours: */
2017-09-01 = 20
2017-10-01 = 20
2017-11-01 = 28.5
  = (13/30)*20 + (17/30)*35 ; (assumed each month has 30 days) 
2017-12-01 = 35

有人愿意帮帮我吗? (我在Azure SQL上)

1 个答案:

答案 0 :(得分:1)

这假设每月最多只有一个小时的变化。如果你有更多,那么你需要围绕比例进行更复杂的计算

select 
    start,  
    round(sum(

    case 
        when [from]>[start] then (datediff(d,[from],finish)+1) * hrs/days
        when [to]<[finish] then (datediff(d,start,[to])+1) * hrs/days
        else hrs end
    ),2)
from
    (select ym as start, EOMONTH(ym) as finish, 
        30
        --datepart(d, EOMONTH(ym)) 
        as days from @months) months
    inner join (    select pers_id, [from], isnull([to], EOMONTH(getdate()))as[to], hrs from @person) p
        on months.finish>=p.[from] and months.start<=p.[to]
group by start