简体   繁体   English

MySQL SUM如果大于和小于

[英]MySQL SUM If More Than & Less Than

I need to sum from price column if they are have more than value 200. 如果价格超过200,我需要从价格栏中加总。

Otherwise, I need to sum if they are have less than value 200. 否则,如果它们的值小于200,我需要求和。

The result I want to grouping them by Date. 结果我想按日期对它们进行分组。

Please see the orders table: 请查看订单表:

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

I want to result like this below: 我希望得到如下结果:

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

And here is what I've tried, but it only show the more than 200 only. 这是我尝试过的,但它只显示了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;

This should work: 这应该工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM