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。
答案 0 :(得分:27)
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子句之前执行