通过 SQL 生成每个客户每月的销售报告,例如按两列分组并对第三列求和

Produce a per customer per month sales report via SQL eg group by two columns and sum the third

我很少写 SQL (Azure SQL) 但是我正在尝试生成每个客户的每月销售总额。

客户:

    |Username     |ID    |
    |user1        |1     |
    |user2        |2     |
    |user3        |3     |

订单:

    |CustomerId   |Month |Total     |
    |1            |1     |275       |
    |1            |1     |10        |
    |2            |1     |100       |
    |1            |3     |150       |
    |2            |2     |150       |
    |2            |2     |65        |
    |3            |2     |150       |

我要生产

|Username     |Month1Total |Month2Total | Month3Total |
|user1        |285         |275         |     150     |
|user2        |100         |215         |      0      |
|user3        |0           |150         |      0      |

我可以做到以下几点

SELECT customerTable.Username Username, SUM(orderTable.OrderTotal) TotalMay
FROM "Order" orderTable
JOIN Customer customerTable ON orderTable.CustomerId = customerTable.Id
WHERE DATENAME(Month, (orderTable.PaidDateUTC)) = 'May'
GROUP BY Username

这将给我每月的输出。但是我不知道如何循环,每月执行一次,然后按用户名分组。

像这样:

SELECT DATENAME(Month, (orderTable.PaidDateUTC)) MonthName, 
   customerTable.Username Username, 
   SUM(orderTable.OrderTotal) TotalMay
FROM "Order" orderTable
JOIN Customer customerTable ON orderTable.CustomerId = customerTable.Id
GROUP BY DATENAME(Month, (orderTable.PaidDateUTC)), Username

您只需将月份名称从 WHERE 子句移动到 GROUP BY。

如果您希望每个月都有一个单独的列,那么试试这个

SELECT customerTable.Username Username
,SUM(iif(ordertable.[month] = 1,orderTable.OrderTotal,0)) TotalJan
,SUM(iif(ordertable.[month] = 2,orderTable.OrderTotal,0)) TotalFeb
,SUM(iif(ordertable.[month] = 3,orderTable.OrderTotal,0)) TotalMar
,SUM(iif(ordertable.[month] = 4,orderTable.OrderTotal,0)) TotalApr
,SUM(iif(ordertable.[month] = 5,orderTable.OrderTotal,0)) TotalMay

FROM "Order" orderTable
JOIN Customer customerTable ON orderTable.CustomerId = customerTable.Id

GROUP BY Username

应该很容易添加剩余的月份

你可以用 case when

  with t1 as
   ( select o.CustomerId,o.Month, sum(Total) as total from
      [Order] 
     group by o.CustomerId,o.Month
  ) select c.Username, 
   case when t1.month=1 then t1.total else 0 end month1,
   case when t1.month=2 then t1.total else 0 end month2,
   case when t1.month=3 then t1.total else 0 end month3 
   from t1 join Customer c on t1.CustomerId=c.ID

或者您可以使用 PIVOT

select c.username, t.* from
(
select * from 
(select * from ord
) src
pivot
( sum(Total) FOR Month IN ([1],[2],[3])
) pvt
) as t join Customer c on t.CustomerId=c.ID

我会简单地 JOIN 进行条件聚合:

SELECT c.Username, 
       SUM(CASE WHEN o.Month = 1 THEN o.Total ELSE 0 END) AS [Month1Total],
       SUM(CASE WHEN o.Month = 2 THEN o.Total ELSE 0 END) AS [Month2Total],
       SUM(CASE WHEN o.Month = 3 THEN o.Total ELSE 0 END) AS [Month3Total],
       . . . 
FROM Customer C INNER JOIN
     Order o
     ON o.CustomerId = c.id
GROUP BY c.Username;