以性能方式计算年总计,期间总计,上年度总计和上期总计

时间:2019-05-21 17:59:31

标签: sql-server window-functions

我有一张销售表。该表包含销售的客户编号,日期和金额。 现在,我必须计算以下值-例如使用期间01/01/2019和03/31/2019

  • 总计01/01/2019至03/31/2019(=期间总计)
  • 总计从01/01/2018至03/31/2018(=去年同期总计)
  • 总计01/01/2019至12/31/2019(=年总计)
  • 总计从01/01/2018至12/31/2018(=上一年总计)

所有这些值均按客户编号分组。

我该如何执行表演?在这种情况下可以使用窗口功能吗?

1 个答案:

答案 0 :(得分:0)

不幸的是,在这种情况下,不能使用窗口功能,因为您不能使用日期在分区内移动,即,将今天客户的所有销售额加起来减去一个月。我想不可能每天为每个客户进行交易(然后可以使用窗口功能)。我将从这样的事情开始:

select 
     CustomerNo
    ,sum(case when [Date] >= '2019-01-01' and [Date] <= '2019-03-31' then Amount else 0 end ) as PeriodTotal
    ,sum(case when [Date] >= '2018-01-01' and [Date] <= '2018-03-31' then Amount else 0 end ) as PreviousYearPeriodTotal
    ,sum(case when [Date] >= '2019-01-01' and [Date] <= '2019-12-32' then Amount else 0 end ) as YearTotal
    ,sum(case when [Date] >= '2018-01-01' and [Date] <= '2018-12-32' then Amount else 0 end ) as PreviousYearTotal
from sales
group by CustomerNo