年度内的价值总和

时间:2016-04-06 14:45:58

标签: mysql date

我目前有一个SQL查询来抓住客户'销售数据并按月和年总和。我想要做的是按季度汇总这些数据。当前查询如下。

SELECT A.*, DATE_FORMAT(C.TxnDate, '%Y-%m') AS FormattedTxnDate, SUM(C.Quantity * D.TotalCost) AS COGS, SUM(C.Quantity * C.Amount) AS Revenue
FROM customer_info A, invoices B, invoice_lines C, inventory D
WHERE A.CustomerID = B.CustomerID 
AND   B.TxnID = C.TxnID
AND   C.ItemID = D.ID
AND B.TxnDate BETWEEN '2013-04-01' AND '2016-04-06'
GROUP BY A.CustomerID, YEAR(B.TxnDate), MONTH(B.TxnDate) ASC

我尝试将查询中的最后一行更改为:

GROUP BY A.CustomerID, YEAR(B.TxnDate), QUARTER(B.TxnDate) ASC

这并没有按预期工作。即使同一季度内的值总计,结果FormattedTxnDate使用给定季度的第一个月与销售信息(因为有问题的客户在实际的第一个月可能没有购买任何东西,如Q2的4月,这意味着FTD&# 39; s月份是5月)。有没有办法使用DATE_FORMAT来显示季度而不是月份?我以为可能有%q选项,但我错了。我应该注意到它可以使用格式化的日期,但它可能比我只是将它们作为宿舍更烦人和烦人。

1 个答案:

答案 0 :(得分:0)

两个GROUP-BY,一个在另一个内。这会给你一个想法:

 select [list attributes of A], year, quarter, sum(revenue) as revenue from 
    (SELECT A.*, 
            DATE_FORMAT(C.TxnDate, '%Y-%m') AS FormattedTxnDate, 
            SUM(C.Quantity * D.TotalCost) AS COGS, 
            SUM(C.Quantity * C.Amount) AS Revenue,
            YEAR(B.TxnDate) as year,
            QUARTER(B.TxnDate) as quarter
     FROM customer_info A, invoices B, invoice_lines C, inventory D
       WHERE A.CustomerID = B.CustomerID 
        AND   B.TxnID = C.TxnID
        AND   C.ItemID = D.ID
        AND B.TxnDate BETWEEN '2013-04-01' AND '2016-04-06'
     GROUP BY A.CustomerID, YEAR(B.TxnDate), MONTH(B.TxnDate) ) as RIP
     GROUP BY [list all attributes of A], year, quarter

我个人会首先进行GROUP-BY,然后加入客户。

另一个选项是:执行B的子查询,在from部分中将该季度添加到原始查询中:

FROM ...,发票B,......

   FROM ..., (select *, quarter(txndate) as quarter From Invoices) as B

那么你可以愉快地在原始查询中按年份,季度