如果我有两张桌子:
学
school_id | class_id | school_location
-------------------------------------------
400 50 Arizona
人员:
staff_id | forename | school_id | wage
------------------------------------------
1 Peter 400 5000
我怎样才能得出在学校工作的员工人数和每所学校的工资。
例如:
school_id | numberofstaff | salary
---------------------------------------
400 | 1 | 5000
我知道我应该加入这样的表:
SELECT school_id
FROM school
INNER JOIN staff
ON school.school_id = staff.school_id
但是我不确定如何进行查询的剩余部分。
SELECT numberofstaff COUNT(numberofstaff) from staff
GROUP BY school_id
Union all
select 'SUM' numberofstaff, COUNT(numberofstaff)
FROM staff
这应该给我的学校ID以及每个school_id的工作人员数量。
答案 0 :(得分:1)
一旦你加入了两张桌子,你就可以统计每个学校的工作人员并计算所有工资:
SELECT sc.school_id,
COUNT(*) as numberofstaff,
SUM(st.wage) as salary
FROM school sc
INNER JOIN staff st
ON sc.school_id = st.school_id
GROUP BY sc.school_id
答案 1 :(得分:1)
试试这种方式
SELECT COUNT(staff.numberofstaff) as numberofstaff , school.school_id as school_id FROM school
INNER JOIN staff
ON school.school_id = staff.school_id
GROUP BY school.school_id;