I have a few tables that make up a media catalog of live/studio music, where each media item has zero-many show dates, CDs and Vinyl associated to it. The query I have at the moment pulls out statistics that results in a tabular set of data for the all the media items available. I'm having trouble now extending the query to include finer grained statistics on each associated table.
Schema:
media(id , title)
cd(media_fk, type)
vinyl(media_fk)
gig(id, date)
media_gigs(gig_fk, media_fk)
Query I have thus far:
SELECT m.id, m.title, COUNT(DISTINCT c.id) as cds, COUNT(DISTINCT v.id) as vinyl, gig.id as gid, gig.date as gdate
FROM media m
LEFT JOIN cd c on m.id = c.media
LEFT JOIN vinyl v on m.id = v.media
LEFT JOIN media_gigs g on m.id = g.media
LEFT JOIN gig gig on g.gig = gig.id
GROUP BY m.id, gig.id;
Which produces:
id | title | cds | vinyl | gid | gdate
---+---------+-----+-------+--------------------------+------------
1 | title 1 | 5 | 1 | may-11-1989-kawasaki | 1989-05-11
1 | title 1 | 5 | 1 | may-13-1989-tokyo | 1989-05-13
2 | title 2 | 6 | 0 | apr-29-1998-nagoya | 1998-04-29
2 | title 2 | 6 | 0 | may-6-1998-tokyo | 1998-05-06
2 | title 2 | 6 | 0 | may-7-1998-tokyo | 1998-05-07
3 | title 3 | 6 | 2 | dec-1-1986-new-york-city | 1986-12-01
3 | title 3 | 6 | 2 | dec-5-1986-quebec-city | 1986-12-05
3 | title 3 | 6 | 2 | nov-19-1986-tokyo | 1986-11-19
3 | title 3 | 6 | 2 | nov-20-1986-tokyo | 1986-11-20
cd.type is an enum type of [silver,cdr,pro-cdr] that I'm wanting to add to the results. So, the the end goal is to have 3 additional columns that are a count of the type of cd associated to each media item. I've not found the correct syntax using COUNT or otherwise to aggregate the cd based on its type, so looking for a push in the right direction. I'm fairly new to SQL so what I have so far may be a bit naive.
Using PG 9.3.