开发者

Mysql SUM with case statement

开发者 https://www.devze.com 2023-03-24 02:05 出处:网络
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:
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

精彩评论

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