0

I have the table teachers (each teacher has got only one module, but module can have many 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

And so on...

And the table modules:

SELECT * from modules
module_id_| title    
--------------------
Int       | varchar    
--------------------
12        | Maths    
56        | PE       
14        | Biology 

And I would like to have a query that give me a list of modules and how many teachers have them and in which year(and sort by this year). So the result would be

PE, 3, 2015, 2016 (in 2015 whas most)
Maths , 3, 2015, 2016
Biology , 1, 2014

EDIT:

Result of the answer below is this, and its not what I wanted:

 count | year | title
-----------------------
   1   | 2015 | Maths 
   1   | 2016 | PE 
   1   | 2015 | Maths 
   1   | 2015 | PE 
   1   | 2015 | PE 
   1   | 2016 | Maths 
   1   | 2014 | Biology 
1
  • I would like to do it in postgresql Commented Feb 25, 2016 at 13:28

1 Answer 1

1

I think it could be something like this:

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;
Sign up to request clarification or add additional context in comments.

2 Comments

its wrong, it doesnt print years in one line, and it lists teachers instead of moules
Your output doesn't seem like output of the query above. Here is what I got: pastebin.com/raw/sWB3z542

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.