使用SQL计算任何给定月份的年初至今和年初至今

时间:2018-06-28 23:34:00

标签: sql sql-server tsql

我正在尝试构建一个图表,以显示我拥有数据的任何给定月份的当前YTD和以前YTD的收入,这些数据是通过SQL生成的,可以随时从视图中检索到报表中。

表看起来像这样

USER1 | MONTH | YEAR | REVENUE | YTD REVENUE | PRIOR YTD REVENUE |
------------------------------------------------------------------
Dan   | Feb   | 2016 |  $75    |   $75       |                   
Bob   | Feb   | 2016 |         |             |                   
Chris | Feb   | 2016 |  $220   |   $220      |     
Dan   | Jan   | 2017 |  $100   |   $100      |     
Bob   | Jan   | 2017 |  $150   |   $150      |     
Chris | Jan   | 2017 |  $200   |   $200      |     
Dan   | Feb   | 2017 |  $100   |   $200      |     $75
Bob   | Feb   | 2017 |  $100   |   $250      |     
Chris | Feb   | 2017 |  $125   |   $225      |     $220

作为构建所述视图的一部分,我如何通过sql来按月计算当前YTD和以前的YTD?我目前没有按照上面的示例按月/年计算YTD,因此在计算PYTD时还需要将其包括在语句中。

当前的SQL查询是

Select USER1, MONTH(Date), YEAR(Date), REVENUE from SOURCE 

1 个答案:

答案 0 :(得分:1)

您将使用窗口功能。这将假设“ month”实际上是一个月数列。这比仅仅一个月更有意义:

select t.*,
       lag(ytd) over (partition by user1, month order by year) as prev_ytd
from (select t.*,
             sum(revenue) over (partition by user1, year order by month) as ytd
      from t
     ) t;

这假定所有用户都有问题月份的数据。

编辑:

如果您缺少行:

with tc as (
      select t.*,
             sum(revenue) over (partition by user1, year order by month) as ytd
      from t
     )
select tc.*, tcprev.ytd
from tc outer apply
     (select top (1) tcprev.ytd
      from tc tcprev
      where tcprev.user1 = tc.user1 and
            tcprev.year = tc.year and
            tcprev.month <= tc.month
      order by tcprev desc
     ) tcprev;