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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL按客户分组的最近15个月销售额相关的知识,希望对你有一定的参考价值。

我想在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   |
+------------+----------+--------+--------+--------+--------+----------+
答案

你可以使用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

以上是关于SQL按客户分组的最近15个月销售额的主要内容,如果未能解决你的问题,请参考以下文章

按月分组的运行计数以汇总销售额

SQL按间隔分组,计数和求和

s-s-rS 分组总和问题

php+mysql中怎么查询最近12个月每个月的数据

如何从当前日期 PHP 获取最近 7 周、7 个月的日期范围?

SQL Server - 我如何对上个月的产品进行排名?