sql - MySQL - 查询 - 多个分组依据

标签 sql mysql group-by aggregate-functions

我有下表,如果 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/

相关文章:

mysql - 从与给定类别 ID 关联的所有子类别级别中选择列表

python - 删除 pandas 数据帧 groupby 中的最后 n 行

mysql - 删除、更新派生表?

C# 检查 MySql 数据库中的日期时间值是否为今天

java - 客户端发送的请求在语法上使用@DateTimeFormat 是不正确的

Mysql CHECKSUM TABLE 不适用于 ndbcluster

mysql - GROUP BY 子句中列的顺序重要吗?

mysql - 在 PHPMYADMIN 中使用 group_concat 将结果显示为 [BLOB - 3B]

SQL 子查询获取特定列

mysql - 如何更快地在列中找到精确匹配,而无需由于非唯一值而选择索引