我有桌子teachers
(每个老师只有一个模块,但模块可以有很多老师):
SELECT * from teachers;
ID | teachers| module_id | year
-------------------------------
Int| varchar | Int | Int
-------------------------------
1 | Jack | 12 | 2015
2 | John | 56 | 2016
3 | Alex | 12 | 2015
4 | Tony | 56 | 2015
5 | Matt | 56 | 2015
6 | Pete | 12 | 2016
7 | Boby | 14 | 2014
等等......
表modules
:
SELECT * from modules
module_id_| title
--------------------
Int | varchar
--------------------
12 | Maths
56 | PE
14 | Biology
我想有一个查询给我一个模块列表,有多少老师拥有它们以及在哪一年(并按今年排序)。所以结果将是
PE, 3, 2015, 2016 (in 2015 whas most)
Maths , 3, 2015, 2016
Biology , 1, 2014
编辑:
以下答案的结果是这个,而不是我想要的:
count | year | title
-----------------------
1 | 2015 | Maths
1 | 2016 | PE
1 | 2015 | Maths
1 | 2015 | PE
1 | 2015 | PE
1 | 2016 | Maths
1 | 2014 | Biology
答案 0 :(得分:1)
我认为它可能是这样的:
SELECT title, count(*), array_agg(distinct year order by year)
FROM modules m
JOIN teachers t ON t.module_id = m.module_id_
GROUP BY title;