开发者

Mysql SUM with case statement

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

Given the above statement does this do the following开发者_如何学JAVA:

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 |
+---------+-----------+---------+------------+

Does this SUM up percent for each row that cumulative = 1. If cumulative != 1 then 0 is summed.


Yes it does! A shorter and cleaner query (IMHO) would be to use IF statement:

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


Why not just to filter out items?

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

In your case each row will be selected and CASE statement has to be applied, I believe with WHERE filter it would be significantly faster because WHERE clause executing before SELECT clause

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜