3

私はmysql 5.1を使用しています。

これが私のDBスキーマです

office
+--------------+----------------+
| office_id    | office_name    |
+--------------+----------------+

employee
+--------------+-----------------------+------------+
| employee_id  | employee_hierarchy_id | office_id  |
+--------------+-----------------------+------------+

employee_hierarchy
+-----------------------+-------------------------------+
| employee_hierarchy_id | employee_hierarchy_description|
+-----------------------+-------------------------------+

number of employees group by employee_hierarchy_idfor eachを数えたいoffice_id

factory_id と employee_hierarchy_id をリストする私のリクエストは次のとおりです。

SELECT office_id, employee_hierarchy_id
FROM office, employee_hierarchy
ORDER BY office_id ASC 

カウントを追加しようとすると、1 行しか表示されません。

SELECT office_id, employee_hierarchy_id, COUNT(*)
FROM office, employee_hierarchy
ORDER BY office_id ASC
4

2 に答える 2

7

WHERE条件とGROUP BY句を追加する

SELECT office_id, employee_hierarchy_id, COUNT(*)
FROM office, employee_hierarchy
WHERE office.factory_id = employee_hierarchy.factory_id
GROUP BY office_id, employee_hierarchy_id
ORDER BY office_id ASC

または推奨される構文

SELECT office_id, employee_hierarchy_id, COUNT(*)
FROM office INNER JOIN employee_hierarchy
        ON office.factory_id = employee_hierarchy.factory_id
GROUP BY office_id, employee_hierarchy_id
ORDER BY office_id ASC

更新1

従業員がいなくてもオフィスの記録を表示したい場合は、を使用LEFT JOINしてください。INNER JOIN

SELECT  a.office_name , c.employee_hierarchy_description,
        COUNT(b.office_ID) totalCount
FROM    office a
        LEFT JOIN employee b
            ON a.office_ID = b.office_ID
        LEFT JOIN employee_hierarchy c
            ON b.employee_hierarchy_id = c.employee_hierarchy_id
GROUP BY a.office_name , c.employee_hierarchy_description
ORDER BY totalCount DESC
于 2012-12-18T15:04:51.757 に答える
2

私はそれを行う別の方法を見つけました、このサブクエリを試してください

SELECT SUM(number_of_employees) as 'number of employee per factory',factory_id
FROM (
SELECT COUNT(*) as 'number_of_employees',employee.factory_id
FROM factory,employee
WHERE factory.factory_id = employee.factory_id
GROUP BY employee.employee_hierarchy_id
) AS tmptbl 
GROUP BY tmptbl.factory_id

お役に立てれば!

于 2012-12-18T15:39:22.970 に答える