我正在尝试从下表中获取总费用,如果设置了Include_Extra
,请使用相应Extra_Seat_Cost
列中的值。我是mysql的新手,所以任何帮助都会非常感激!
+-----------+-----------------+---------------+
| ID | Cost | Extra_Seat_Cost | Include_Extra |
+-----------+-----------------+---------------+
| 3 | 20 | 15 | 1 |
| 4 | 10 | 5 | 0 |
+----+------+-----------------+---------------+
结果应该总计= $ 45
答案 0 :(得分:1)
您可以将SUM
与CASE 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;