我使用以下代码创建了一个名为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 :(得分:2)
根据类型进行透视。由于您不知道类型的数量,您需要使用动态SQL使其动态化。请参阅下面的示例。
您可以更改聚合以满足您的需求。在下面的示例中,我按年计算ID和分组。
在Pivot之前
<强>代码强>
CREATE TABLE tbl
(
Year int,
Album varchar(255),
Artist varchar(255),
Label varchar(255),
Genre varchar(255),
id int
)
;
INSERT INTO tbl
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)
Select * from tbl
Declare @Query_ nvarchar(MAX)
Declare @Cols_For_Pivot_ nvarchar(MAX)
--Get unique list of metrics in Var_Col for pivot.
SELECT @Cols_For_Pivot_= COALESCE(@Cols_For_Pivot_ + ',','') + QUOTENAME(Genre)
FROM (SELECT DISTINCT Genre FROM dbo.tbl) AS PivotExample
SET @Query_ =
N'SELECT Year, ' + @Cols_For_Pivot_ + '
FROM [dbo].[tbl]
PIVOT( Count(id)
FOR Genre IN (' + @Cols_For_Pivot_ + ')) AS P
GROUP BY Year, ' + @Cols_For_Pivot_ + ''
--Execute dynamic query
EXEC sp_executesql @Query_
数据透视后