MySQL计数行

时间:2009-08-24 02:18:24

标签: mysql count

如何根据内容计算行? 假设我有这样的表

[表a]

ID_COMPANY   |   NAME
-----------------------------
A1           |   COMPANY A


[表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

我怎样才能得到这样的结果?

ID_COMPANY  |    NAME   |  TOTAL_MANAGER  | TOTAL_STAFF_DEPT  | TOTAL_CUST
----------------------------------------------------------------------------
A1          | COMPANY A |              1  |                2  |          1

thx guys

5 个答案:

答案 0 :(得分:7)

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`

SUM的标准可能需要调整,因为我不明白你在那里想要实现的目标。

答案 1 :(得分:2)

使用子查询并计算结果。

有缺陷的“psuedo-sql”:

select ID_COMPANY, NAME,
count(select * from b where type like "MAN*) as "TOTAL_MANAGER",
count(select * from b where type like "DEPT*") as "TOTAL_STAFF_DEPT",
count(select * from b where type like "CUST*") as "TOTAL_CUST"

当我说有缺陷的时候,我的意思是我没有尝试过这个,而我只是试图让这个想法得到解决而不是给你一些东西来复制&糊。

答案 2 :(得分:1)

类似的东西:

SELECT 
    ID_COMPANY, 
    NAME, 
    (SELECT COUNT(ID_COMPANY) FROM table_b WHERE ID_COMPANY = table_a.ID_Company and TYPE = 'MANAGER') as TOTAL_MANAGER,
    (SELECT COUNT(ID_COMPANY) FROM table_b WHERE ID_COMPANY = table_a.ID_Company and TYPE = 'DEPT001') as DEPT001C,
    (SELECT COUNT(ID_COMPANY) FROM table_b WHERE ID_COMPANY = table_a.ID_Company and TYPE = 'DEPT002') as DEPT002C,
FROM table_a
GROUP BY ID_COMPANY

答案 3 :(得分:0)

扩展Matthew的回复我建议你使用UNIONs和GROUP BYs。如:

SELECT ID_COMPANY, NAME, COUNT(USER) AS TOTAL_MANAGER FROM TABLE_B WHERE TYPE LIKE 'MANAGER' GROUP BY ID_COMPANY

您需要将这些结果合并以获得一个结果集。

答案 4 :(得分:0)

......这是JOIN方法:

SELECT
  a.id_company,
  a.name,
  mgr.cnt  AS total_manager,
  dept.cnt AS total_staff_dept,
  cust.cnt AS total_cust
FROM
  a
  JOIN
  (SELECT id_company, COUNT(*) AS cnt
   FROM b WHERE type = 'MANAGER' GROUP BY id_company)  mgr
    ON a.id_company = mgr.id_company
  JOIN
  (SELECT id_company, COUNT(*) AS cnt
   FROM b WHERE type LIKE 'DEPT%' GROUP BY id_company) dept
    ON a.id_company = dept.id_company
  JOIN
  (SELECT id_company, COUNT(*) AS cnt
   FROM b WHERE type = 'CUSTOMR' GROUP BY id_company)  cust;

...这给了我(假设没有比你显示的更多的记录):

+------------+------+---------------+------------------+------------+
| id_company | name | total_manager | total_staff_dept | total_cust |
+------------+------+---------------+------------------+------------+
| A1         | foo  |             1 |                2 |          2 |
+------------+------+---------------+------------------+------------+
1 row in set (0.00 sec)