how can I count row based on its contents?
assumed I have table like this
[table a]
ID_COMPANY | NAME
-----------------------------
A1 | COMPANY A
[table b]
ID_COMPANY | USER | TYPE
--------------------------------------
A1 | USER A | MANAGER
A1 | USER B | DEPT001
A1 | USER C | CUSTOMR
A1 | USER D | DEPT002
A1 | USER E | CUSTOMR
how can i get the result like this?
ID_COMPANY | NAME | TOTAL_MANAGER | TOTAL_STAFF_DEPT | TOTAL_CUST
----------------------------------------------------------------------------
A1 | COMPANY A | 1 | 2 | 1
thx guys
SELECT
`table_a`.`ID_COMPANY`,
`NAME`,
SUM(IF(`TYPE` = 'MANAGER', 1, 0)) AS `TOTAL_MANAGER`,
SUM(IF(`TYPE` LIKE 'DEPT%', 1, 0)) AS `TOTAL_STAFF_DEPT`,
SUM(IF(`TYPE` = 'CUSTOMR', 1, 0)) AS `TOTAL_CUST`
FROM `table_a`
JOIN `table_b`
USING (`ID_COMPANY`)
GROUP BY `table_a`.`ID_COMPANY`
The criteria for the SUMs will probably need tweaking because I don't understand exactly what you're trying to achieve there.
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