我使用以下代码创建了一个名为tbl
的表:
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)
;
我想运行一个查询来显示每年的流派数量,而不会因为Label
列而重复计算。我想要这个:
Year, hip hop, pop-dance
1990, 1, 1
我必须运行什么查询才能获得我想要的内容?
答案 0 :(得分:4)
因为您无法使用pivot
,所以可以执行此操作。
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
答案 1 :(得分:1)
接受的答案对我有用。
在这里,我添加了一个更复杂的案例,如果有人需要的话,可以使用join。
另请参阅:
Combining 2 SQL queries and getting result set in one
我的例子:
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