Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - query - multiple group by

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 | 
+-----------+--------------------------------+
like image 586
Josh Avatar asked Feb 16 '11 19:02

Josh


2 Answers

Use:

   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

If you don't need to see the rows with zero counts:

   SELECT client_id, 
          COUNT(DISTINCT type)
     FROM FOO 
    WHERE type = 'printer'
 GROUP BY type, client_id;
like image 157
OMG Ponies Avatar answered Oct 29 '22 17:10

OMG Ponies


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, and 0 otherwise, try max instead of sum:

MAX(IF(type = 'printer', 1,0))
^^^

EDIT: To count the number of distinct printers, you could use a subquery:

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
like image 44
Andomar Avatar answered Oct 29 '22 16:10

Andomar