请帮助我。这个类别是动态的,将来有多少类别必须在旋转输出中显示。
我有一张这样的桌子。
Create table [Pivot_Check]
(
[Id] Int Identity(1,1)
,[Category] Varchar(1)
)
Insert into [Pivot_Check] Values('A')
Insert into [Pivot_Check] Values('B')
Insert into [Pivot_Check] Values('A')
Insert into [Pivot_Check] Values('B')
Insert into [Pivot_Check] Values('C')
Insert into [Pivot_Check] Values('D')
Insert into [Pivot_Check] Values('C')
Insert into [Pivot_Check] Values('D')
Select * from [Pivot_Check]
表数据将是这样的!
Id Category
1 A
2 B
3 A
4 B
5 C
6 D
7 C
8 D
如何获得这样的输出?
Id A B C D
```````````````````````````
1 A NULL NULL NULL
2 NULL B NULL NULL
3 A NULL NULL NULL
4 NULL B NULL NULL
5 NULL NULL C NULL
6 NULL NULL NULL D
7 NULL NULL C NULL
8 NULL B NULL D
答案 0 :(得分:1)
你可以写成:
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT @ColumnName= ISNULL(@ColumnName + ',','')
+ QUOTENAME(Category)
FROM (SELECT DISTINCT Category FROM [Pivot_Check]) AS [Pivot_Check]
--Prepare the PIVOT query using the dynamic
SET @DynamicPivotQuery =
N'SELECT Id, ' + @ColumnName + '
FROM [Pivot_Check]
PIVOT(Min([Category])
FOR [Category] IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery
答案 1 :(得分:0)
你走了:
SELECT id,
CASE WHEN Category = 'A' THEN 'A' ELSE Null END AS A,
CASE WHEN Category = 'B' THEN 'B' ELSE Null END AS B,
CASE WHEN Category = 'C' THEN 'C' ELSE Null END AS C,
CASE WHEN Category = 'D' THEN 'D' ELSE Null END AS D
FROM Pivot_Check
ORDER BY id;