MySQL - 查询 - 多个组

时间:2011-02-16 19:35:48

标签: sql mysql group-by aggregate-functions

我有下表,其中我正在尝试SUM,如果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 | 
+-----------+--------------------------------+

4 个答案:

答案 0 :(得分:8)

使用:

   SELECT x.client_id,
          COUNT(DISTINCT y.type) 
     FROM FOO x
LEFT JOIN FOO y ON y.client_id = x.client_id
               AND y.type = 'printer'
 GROUP BY x.client

如果您不需要查看零计数的行:

   SELECT client_id, 
          COUNT(DISTINCT type)
     FROM FOO 
    WHERE type = 'printer'
 GROUP BY type, client_id;

答案 1 :(得分:7)

有三行,类型为printerSum将它们全部添加,然后返回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

编辑:要计算不同打印机的数量,可以使用子查询:

{{1}}

答案 2 :(得分:1)

SELECT client_id, if( `type` = 'printer', 1, 0 )
FROM foo
GROUP BY TYPE , client_id

答案 3 :(得分:0)

SELECT distinct client_id, 
     (IF(type = 'printer', 1,0)) 
FROM FOO 

(我猜:我不熟悉IF(..))