我有下表,如果 type = 'printer',我在其中尝试求和,但是,我不想计算重复的 client_id。所以我期待这样的事情:
+------+-----------+-----------+
| k_id | client_id | type |
+------+-----------+-----------+
| 1 | 100 | pc |
| 2 | 101 | printer |
| 3 | 101 | printer |
| 4 | 101 | printer |
| 5 | 102 | cellphone |
+------+-----------+-----------+
查询:
SELECT client_id,
SUM(IF(type = 'printer', 1,0))
FROM FOO
GROUP BY type, client_id;
结果:
+-----------+--------------------------------+
| client_id | SUM(IF(type = 'printer', 1,0)) |
+-----------+--------------------------------+
| 102 | 0 |
| 100 | 0 |
| 101 | 3 |
+-----------+--------------------------------+
预期结果:
+-----------+--------------------------------+
| client_id | SUM(IF(type = 'printer', 1,0)) |
+-----------+--------------------------------+
| 102 | 0 |
| 100 | 0 |
| 101 | 1 |
+-----------+--------------------------------+
最佳答案
打印机
类型共有三行。 Sum
将它们全部相加,返回 3。
如果您希望看到带有打印机的行为 1
,否则为 0
,请尝试使用 max
而不是 sum
:
MAX(IF(type = 'printer', 1,0))
^^^
编辑:要计算不同打印机的数量,您可以使用子查询:
SELECT client_id
, (
select count(*)
from FOO as f2
where f1.client_id = f2.client_id
and type = 'Printer'
)
FROM FOO as f1
GROUP BY
client_id
关于sql - MySQL - 查询 - 多个分组依据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5021243/