3

I made a table called tbl with this code:

CREATE TABLE tbl
    (
      `Year` int, 
      `Album` varchar(255),
      `Artist` varchar(255),
      `Label` varchar(255),
      `Genre` varchar(255),
      `id` int
    )
;

INSERT INTO tbl
    (
      `Year`,
      `Album`,
      `Artist`,
      `Label`,
      `Genre`,
      `id`
    )
VALUES
    (1990, "Greatest Hits", "The Best", "Least Def", "hip hop", 123),
    (1990, "Greatest Hits", "The Best", "Roofless", "hip hop", 123),
    (1990, "4-Boyz", "3 Guyz", "Pacific", "pop-dance", 23),
    (1990, "4-Boyz", "3 Guyz", "Atlantic", "pop-dance", 23)
;

I want to run a query to show me the count of genres for each year, without double counting because of the Label column. I want this:

Year, hip hop, pop-dance
1990, 1, 1

What query must I run to get what I want?

Username
  • 3,463
  • 11
  • 68
  • 111

2 Answers2

5

Because you can't use pivot, you can do this.

select year,
count(distinct case when `Genre` = 'hip hop' then 1 end) as hiphop,
count(distinct case when `Genre` = 'pop-dance' then 1 end) as popdance
from tbl
group by year
Vamsi Prabhala
  • 48,685
  • 4
  • 36
  • 58
  • http://www.sqlfiddle.com/#!5/763ad/3 If they want to mess around with it anymore. – Dresden May 11 '16 at 19:01
  • 2
    If I add more rows with more different Genres, is there a way to take those into account without having to add more `count(distinct case when `Genre` = 'new genre' then 1 end) as newgenre` statements? – Username May 11 '16 at 20:47
  • 1
    No,unfortunately afaik. You will have to do this manually. If it were SQL Server or Oracle you would have had an option of doing a dynamic pivot. – Vamsi Prabhala May 11 '16 at 20:49
  • @vkp How about MySQL or PostgreSQL? – Username May 11 '16 at 22:26
1

The accepted answer worked for me.

I add here a more complex case, with join, in case someone needs.

see also:

Combining the results of two SQL queries as separate columns

my example:

    select Info.*, Roots.*, ColeColeFit.*, f10.*, f20k.*
    from Info
    join (select * from Data where Frequency = 10) as f10
      on f10.Info_ID = Info.id
    join (select * from Data where Frequency = 20000) as f20k
      on f20k.Info_ID = Info.id
    join Roots
      on Info.File_Num = Roots."Plant number"
    join ColeColeFit
      on ColeColeFit.id = Info.id
Jeremy Field
  • 652
  • 7
  • 12
Peruz
  • 403
  • 3
  • 10