Mysql Sum条件

时间:2015-11-22 21:50:15

标签: mysql sql

我正在尝试从下表中获取总费用,如果设置了Include_Extra,请使用相应Extra_Seat_Cost列中的值。我是mysql的新手,所以任何帮助都会非常感激!

+-----------+-----------------+---------------+
| ID | Cost | Extra_Seat_Cost | Include_Extra |
+-----------+-----------------+---------------+
|  3 |   20 |      15         |       1       |
|  4 |   10 |      5          |       0       |
+----+------+-----------------+---------------+

结果应该总计= $ 45

1 个答案:

答案 0 :(得分:1)

您可以将SUMCASE WHEN

一起使用
SELECT SUM(Cost + CASE WHEN Include_Extra = 1   --if Include_Extra is bool delete = 1
                       THEN COALESCE(Extra_Seat_Cost,0) 
                       ELSE 0 END) AS total
FROM table_name;

SqlFiddleDemo

我已添加COALESCE,以防Extra_Seat_Cost可以为空。数字+ NULL生成NULL

<小时/> 如果您使用分组列:

SELECT group_column, SUM(Cost + CASE WHEN Include_Extra = 1 
                                     THEN COALESCE(Extra_Seat_Cost,0) 
                                     ELSE 0 END) AS total
FROM table_name;
GROUP BY group_column;