Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL count row

Tags:

mysql

count

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

like image 252
Daniel Budihardja Avatar asked Dec 20 '25 00:12

Daniel Budihardja


1 Answers

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.

like image 145
chaos Avatar answered Dec 21 '25 14:12

chaos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!