MySQL SUM如果超过&少于

时间:2016-05-11 05:52:01

标签: mysql sum

如果价格超过200,我需要从价格列求和。

否则,如果它们的值小于200,我需要求和。

我希望按日期对结果进行分组。

请参阅订单表:

price       date_transaction
537         2014-03-28 11:44:40
123         2014-03-28 14:35:21
96          2014-03-28 15:43:17
341         2014-03-28 16:12:42
309         2014-03-29 15:47:48
223         2014-03-29 19:22:28
115         2014-03-29 23:31:34
109         2014-03-29 23:44:16

我想在下面得到如下结果:

date_transaction    sum_of_two_hundred_or_more      sum_of_less_than_200
2014-03-28          878                             219
2014-03-29          532                             224
2014-03-30          0                               0
2014-03-31          0                               0

这就是我尝试过的,但它只显示了200多个。

SELECT
DISTINCT DATE(date_transaction) AS date_transaction,
SUM(price) AS sum_of_two_hundred_or_more
FROM orders
WHERE price > 200
AND date_transaction BETWEEN '2014-03-26' AND '2014-03-31' + INTERVAL 1 DAY
GROUP BY DATE(date_transaction)
ORDER BY DATE(date_transaction) ASC;

1 个答案:

答案 0 :(得分:3)

这应该有效:

SELECT DATE(date_transaction) AS date_transaction,
    SUM (CASE WHEN price >= 200 THEN price ELSE 0 END) AS sum_of_two_hundred_or_more
    SUM (CASE WHEN price < 200 THEN price ELSE 0 END) AS sum_of_two_hundred_less
FROM orders
WHERE date_transaction BETWEEN '2014-03-26' AND '2014-03-31' + INTERVAL 1 DAY
GROUP BY DATE(date_transaction)
ORDER BY DATE(date_transaction) ASC