MySQL - 查询 - 多个分组依据
我有下表,其中我尝试对 type = 'printer' 进行求和,但是,我不想计算重复的 client_ids。所以我期望这样的结果:
+------+-----------+-----------+
| 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 |
+-----------+--------------------------------+
I have the following table, in which I'm trying to SUM if type = 'printer', however, I would like not to count repeat client_ids. So I expect something like this:
+------+-----------+-----------+
| k_id | client_id | type |
+------+-----------+-----------+
| 1 | 100 | pc |
| 2 | 101 | printer |
| 3 | 101 | printer |
| 4 | 101 | printer |
| 5 | 102 | cellphone |
+------+-----------+-----------+
Query:
SELECT client_id,
SUM(IF(type = 'printer', 1,0))
FROM FOO
GROUP BY type, client_id;
Result:
+-----------+--------------------------------+
| client_id | SUM(IF(type = 'printer', 1,0)) |
+-----------+--------------------------------+
| 102 | 0 |
| 100 | 0 |
| 101 | 3 |
+-----------+--------------------------------+
Expected result:
+-----------+--------------------------------+
| client_id | SUM(IF(type = 'printer', 1,0)) |
+-----------+--------------------------------+
| 102 | 0 |
| 100 | 0 |
| 101 | 1 |
+-----------+--------------------------------+
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一共有三行,其类型为
打印机
。Sum
将它们全部相加,并返回 3。如果您希望看到带有打印机的行的
1
,否则看到0
,请尝试 < code>max 而不是sum
:编辑:要计算不同打印机的数量,您可以使用子查询:
There are three rows with a type of
printer
.Sum
adds them all up, and returns 3.If you'd like to see
1
for rows with printers, and0
otherwise, trymax
instead ofsum
:EDIT: To count the number of distinct printers, you could use a subquery:
使用:
如果您不需要查看计数为零的行:
Use:
If you don't need to see the rows with zero counts:
(我猜:我不熟悉 IF(..))
(I'm guessing: I'm not aquainted with IF(..))