如何对联接表中的最后12个月的数据求和

时间:2019-01-17 22:57:29

标签: mysql sql

我有两个联接表,customers和Order,均由CustomerPK链接。

关于客户的故事,我试图汇总每个客户的总支出(从“加入”到“订单”表中获取总和),然后计算该客户的最近12个月的支出,这是最后一行无法正常工作,在这里是我的代码:

SELECT
customers.CustomerPk,
customers.CustomerCode,
customers.CustomerName,
customers.AddressLine1,
customers.AddressLine2,
customers.AddressLine3,
customers.AddressLine4,
customers.AddressLine5,
customers.Town,
customers.County,
customers.PostCode,
customers.Country,
SUM(orders.OrderValue) AS `Total Spend`,
SUM(orders.OrderValue) WHERE orders.OrderDate >= curdate() - interval 1 year as `Last 12 Month Spend`
FROM customers
LEFT OUTER JOIN orders ON customers.CustomerPk = orders.CustomerFk
GROUP BY customers.CustomerPk, customers.CustomerCode, customers.CustomerName, customers.AddressLine1, customers.AddressLine2, customers.AddressLine3, customers.AddressLine4, customers.AddressLine5, customers.Town, customers.County, customers.PostCode, customers.Country

该表一直工作到我添加以下行:     SUM(orders.OrderValue)WHERE order.OrderDate> = curdate()-间隔1年为Last 12 Month Spend

我需要此WHERE语句仅应用于此行,而不应用于整个表,因为它将删除结果。

非常感谢

1 个答案:

答案 0 :(得分:2)

您不能在列中添加WHERE子句。但是,如果您只想对满足条件的值求和,则可以在CASE中使用sum()表达式。如果满足您的条件,请返回该值,该值应加到总和上。否则返回零-如果添加零,则总和不会改变。

...
sum(CASE
      WHEN orders.orderdate >= curdate() - interval 1 year THEN
        orders.ordervalue       
      ELSE
        0
    END) `Last 12 Month Spend`
...