来自日期范围的MySQL SUM列

时间:2016-05-10 09:39:35

标签: mysql sum

如何对每个日期范围中的列进行求和。

我需要总结价格列和&折扣列然后根据日期行生成它们。

在这种情况下,我为 39 选择了 order_id ,请参阅下表。

以下是订单表:

id      order_id        price       price_disc      date_transaction
1       39              537         25              2014-03-28 11:44:40
2       39              323         0               2014-03-28 16:12:42
3       38              309         11              2014-03-29 15:47:48
4       39              223         16              2014-03-29 19:22:28
5       37              304         19              2014-03-30 23:31:34
6       38              109         7               2014-03-31 09:12:16
7       38              223         0               2014-03-31 17:00:35
8       38              116         9               2014-04-01 20:32:27
9       38              296         0               2014-04-02 16:45:00
10      39              482         20              2014-04-03 12:42:03
11      39              371         12              2014-04-03 20:02:10
12      36              293         13              2014-04-03 21:09:45
13      39              299         0               2014-04-03 23:28:10
14      39              403         22              2014-04-04 08:06:13

我想要这样的结果:

date_transaction    total_price     total_price_disc
2014-03-28          860             25
2014-03-29          223             16
2014-03-30          0               0
2014-03-31          0               0
2014-03-01          0               0
2014-03-02          0               0
2014-03-03          1152            32
2014-03-04          403             22
2014-03-05          0               0
2014-03-06          0               0

这就是我尝试过但只取得date_transaction&的结果。仅限total_price。

SELECT
DISTINCT DATE_FORMAT(date_transaction, '%Y-%m-%d') AS date_transaction,
COALESCE(SUM(price), 0) AS total_price
FROM orders
WHERE order_id = 39
AND date_transaction BETWEEN '2014-03-28' AND '2014-04-06' + INTERVAL 1 DAY
GROUP BY DATE_FORMAT(date_transaction, '%Y-%m-%d')
ORDER BY date_transaction ASC;

1 个答案:

答案 0 :(得分:0)

使用DATE()功能查看日期。

SELECT
DISTINCT DATE(date_transaction) AS date_transaction,
SUM(price) AS total_price,
SUM(price_disc) AS total_price_disc
FROM orders
WHERE order_id = 39
AND DATE(date_transaction) BETWEEN '2014-03-28' AND '2014-04-06' + INTERVAL 1 DAY
GROUP BY DATE(date_transaction)
ORDER BY DATE(date_transaction) ASC;