带有case语句的Mysql SUM

时间:2011-07-29 19:30:44

标签: mysql sql sum case

SELECT 
    SUM(
        CASE 
           WHEN cumulative = 1 
           THEN percent 
           ELSE 0 
        END) 
FROM phppos_items_taxes;

鉴于上述声明,请执行以下操作:

mysql> select * FROM phppos_items_taxes;
+---------+-----------+---------+------------+
| item_id | name      | percent | cumulative |
+---------+-----------+---------+------------+
|       1 | Tax 1     |    8.00 |          0 |
|       1 | Tax 2     |   10.00 |          1 |
|       3 | Sales Tax |    8.00 |          0 |
|       4 | Tax 1     |   20.00 |          0 |
|       4 | Tax 2     |   20.00 |          0 |
+---------+-----------+---------+------------+

对于累计= 1的每一行,这是否会累计百分比。如果累计!= 1,则归零0。

2 个答案:

答案 0 :(得分:27)

是的,确实如此! 更简洁更清晰的查询(IMHO)将使用IF语句:

SELECT SUM(IF(cumulative = 1, `percent`, 0)) FROM phppos_items_taxes;

答案 1 :(得分:7)

为什么不过滤掉物品?

SELECT 
    SUM(ISNULL(percent, 0)) 
FROM 
    phppos_items_taxes
WHERE 
    cumulative = 1

在你的情况下,每一行都将被选中并且必须应用CASE语句,我相信WHERE过滤器会明显更快,因为 WHERE子句在SELECT子句之前执行