SQL按客户分组的最近15个月的销售

时间:2019-03-05 03:06:21

标签: sql sql-server tsql pivot

我想在sql中输出一个包含每个客户每月销售额的表。每列应对应另一个月份。

第一列应为当月示例,我的sql列为:

  • 客户
  • 发票日期
  • 销售

原始表如下:

+------------+------------+---------+
|  Customer  |  invdate   | sales   |
+------------+------------+---------+
| Best Buy   | 03-12-2019 |   433   |
| Walmart    | 03-15-2019 |   543   |
| Home Depot | 12-12-2018 |      32 |
+------------+------------+---------+

所需的输出:

+------------+----------+--------+--------+--------+--------+----------+
|  Customer  | March 19 | Feb 19 | Jan 19 | Dec 18 | Nov 18 | Oct 18   |
+------------+----------+--------+--------+--------+--------+----------+
| Home Depot |      100 |    300 |    244 |     32 |    322 |     43   |
| Walmart    |      543 |    222 |    234 |     12 |    234 |     34   |
| Bestbuy    |      433 |    323 |    323 |     23 |    433 |     34   |
+------------+----------+--------+--------+--------+--------+----------+

1 个答案:

答案 0 :(得分:0)

您可以使用group by,sum和case来达到良好效果,如下所示:

select
  customer,
  sum(case when year(invdate) = year(getdate) and month(invdate) = month(getdate())   then sales else o end),
  sum(case when year(invdate) = year(dateadd(m,1,getdate))
           and month(invdate) = month(dateadd(m,1,getdate())) then sales else o end),
  sum(case when year(invdate) = year(dateadd(m,2,getdate))
           and month(invdate) = month(dateadd(m,2,getdate())) then sales else o end),
  sum(case when year(invdate) = year(dateadd(m,3,getdate))
           and month(invdate) = month(dateadd(m,3,getdate())) then sales else o end),
  sum(case when year(invdate) = year(dateadd(m,4,getdate))
           and month(invdate) = month(dateadd(m,4,getdate())) then sales else o end),
  sum(case when year(invdate) = year(dateadd(m,5,getdate))
           and month(invdate) = month(dateadd(m,5,getdate())) then sales else o end)
from tableyoudidnotgivethenameof
group by customer