我有一张桌子学生:
student_id | name | course
-------------------------------------
1 | Jack | Comp_Sci
2 | John | Maths
3 | Matt | Comp_Sci
4 | Pete | Biology
表部门:
course | department
-------------------------
Comp_Sci | Comp_and_Math
Maths | Comp_and_Math
Biology | Bio_and_Chem
表using_computers
computer_id | student_id
-------------------------
1 | 2
2 | 2
2 | 3
2 | 4
3 | 1
4 | 2
4 | 4
和台式电脑
computer_id | name
---------------------
1 | Apple
2 | Dell
3 | Asus
4 | Acer
我想列出像这样的部门中所有使用过的电脑
Comp_and_Maths: Apple 1, Dell 2, Asus 1, Acer 1, sum: 5
Bio_and_Chem: Dell 1, Acer 1 , sum:2
我已经写了2个查询,但我不知道如何连接它们:
SELECT Departments.department, obj_in_class.list_ids
FROM Departments LEFT JOIN
(SELECT Departments.course, array_agg(students.student_id) AS list_ids
FROM Departments
LEFT JOIN students
ON Departments.course = students.course GROUP BY Departments.course) AS obj_in_class
ON Departments.course = obj_in_class.course GROUP BY Departments.department, obj_in_class.list_ids;
(SELECT students.student_id AS id, array_agg(m.name) AS computers
FROM students LEFT JOIN
(SELECT computers.name, using_computers.student_id FROM using_computers LEFT JOIN computers ON using_computers.computer_id = computers.computer_id) AS m
ON students.student_id = m.student_id
GROUP BY students.student_id) AS students_with_computers;
答案 0 :(得分:2)
它不会重复使用您之前的查询:
SELECT
-- aggregate computer name and count as a string
grouped.department || ': ' ||
array_to_string(array_agg(grouped.name || ' ' || grouped.count), ', ')
-- sum all the counts
|| ', sum: ' || sum(grouped.count)
FROM (
SELECT
D.department,
C.name,
count(C.name) -- count computers' name per department
FROM Departments D
JOIN students S USING (course)
JOIN using_computers UC USING (student_id)
JOIN computers C USING (computer_id)
GROUP BY D.department, C.name
ORDER BY D.department, C.name
) grouped
GROUP BY grouped.department
;
我们的想法是按部门和计算机加入每个表和组,以获得每个部门(计算机品牌)的计数。这是在grouped
子选择中完成的。我们现在拥有所需的每一项数据和计数。
然后我们按部门分组并汇总所有内容。