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 |
+-----------+--------------------------------+
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With