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

问题描述 投票:0回答:1

我想在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   |
+------------+----------+--------+--------+--------+--------+----------+
sql sql-server tsql pivot
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.