SQL计算单独列中不同日期范围的数据

时间:2018-01-23 22:10:01

标签: sql sql-server

假设我有以下格式的原始表数据:

UserID | DateWorked | HoursWorked | AmountPaid
----------------------------------------------
1      | 11/01/17   |     5.00    |    20.00
1      | 11/02/17   |     3.00    |    5.00
2      | 11/15/17   |     10.00   |    50.00

在我目前的状态下,我有一个SP(RawdataSP),它通过输入日期范围(@BeginDate和@EndDate)返回具有上述结构的原始数据。

我写了另一个SP,我在其中声明了2个表变量来存储2个执行RawdataSP的结果,如下所示:

declare @tablemonth table(...)
declare @tableytd table(...)
insert into @tablemonth execure RawDataSP @BeginDate = @BeginDate, @EndDate = @EndDate
insert into @tableytd execure RawDataSP @BeginDate = @YTDBeginDate, @EndDate = @YTDEndDate

它可以正常工作,但结果是2个单独的表。

我正在尝试在单个表的单独列中显示不同日期范围的计数:1表示月份范围(@BeginDate和@EndDate之间)和1表示YTD范围(1月1日到1月1日之间) @BeginDate - 1day)

我想要的最终结果如下:

1)我们假设我在2017年11月运行SP

2)结果表将如下格式

columns... | TotalHoursMonth | TotalPaidMonth  | TotalHoursYTD  | TotalPaidYTD
           ---------------------------------------------------------------------
           |hours counts     | Amount paid     |hours counts    | Amount paid      |
           |between 11/01/17 | between 11/01/17|between 01/01/17| between 01/01/17 |
           |and 11/30/17     | and 11/30/17    |and 10/30/17    | and 10/30/17     |

我正在努力完成最后一部分。 我可以使用@YTDBeginDate和@EndDate之间的范围执行一次SP(以获取完整日期的数据范围),然后将其拆分为上面的单独列吗?

1 个答案:

答案 0 :(得分:3)

您可以使用条件聚合:

select UserID,
       sum(case when dateworked >= '2017-11-01' and dateworked < '2017-12-01' then hoursworked else 0
           end) as month_hours,
       sum(case when dateworked >= '2017-11-01' and dateworked < '2017-12-01' then AmountPaid else 0
           end) as month_amount,
       sum(case when dateworked >= '2017-01-01' and dateworked < '2018-01-01' then hoursworked else 0
           end) as ytd_hours,
       sum(case when dateworked >= '2017-01-01' and dateworked < '2018-01-01' then AmountPaid else 0
           end) as ytd_amount
from t
group by UserID;

使用变量,这看起来像:

select UserID,
       sum(case when dateworked >= @BeginDate and dateworked < @EndDate then hoursworked else 0
           end) as month_hours,
       sum(case when dateworked >= @BeginDate and dateworked < @EndDate then AmountPaid else 0
           end) as month_amount,
       sum(case when year(dateworked) = year(@BeginDate) and dateworked < @EndDate then hoursworked else 0
           end) as ytd_hours,
       sum(case when year(dateworked) = year(@BeginDate) and dateworked < @EndDate then AmountPaid else 0
           end) as ytd_amount
from t
group by UserID;

如果您想要这一点,请删除UserIdGROUP BY