SQL数据透视表
问题描述:
,我有以下数据:SQL数据透视表
ID Data
1 tera
1 add
1 alkd
2 adf
2 add
3 wer
4 minus
4 add
4 ten
我试图使用数据透视表,行推入1排,每ID多列。 所以如下:
ID Custom1 Custom2 Custom3 Custom4..........
1 tera add alkd
2 adf add
3 wer
4 minus add ten
我迄今以下查询:
INSERT INTO @SpeciInfo
(ID, [Custom1], [Custom2], [Custom3], [Custom4], [Custom5],[Custom6],[Custom7],[Custom8],[Custom9],[Custom10],[Custom11],[Custom12],[Custom13],[Custom14],[Custom15],[Custom16])
SELECT
ID,
[Custom1],
[Custom2],
[Custom3],
[Custom4],
[Custom5],
[Custom6],
[Custom7],
[Custom8],
[Custom9],
[Custom10],
[Custom11],
[Custom12],
[Custom13],
[Custom14],
[Custom15],
[Custom16]
FROM SpeciInfo) p
PIVOT
(
(
[Custom1],
[Custom2],
[Custom3],
[Custom4],
[Custom5],
[Custom6],
[Custom7],
[Custom8],
[Custom9],
[Custom10],
[Custom11],
[Custom12],
[Custom13],
[Custom14],
[Custom15],
[Custom16]
)
) AS pvt
ORDER BY ID;
我需要的16场,但我不完全相信我做什么FROM子句,或者如果我米甚至这样做是否正确?
感谢
答
如果你追求的是动态生成的列,即通常被称为动态交叉,不能在T-SQL来完成,而不诉诸动态SQL(构建查询字符串),这是不建议。相反,您应该在中间层或报告应用程序中构建该查询。
如果你只是想一个静态的解决方案,替代使用的你寻找可能看起来像这样在SQL Server 2005或更高版本什么PIVOT:
With NumberedItems As
(
Select Id, Data
, Row_Number() Over(Partition By Id Order By Data) As ColNum
From SpeciInfo
)
Select Id
, Min(Case When Num = 1 Then Data End) As Custom1
, Min(Case When Num = 2 Then Data End) As Custom2
, Min(Case When Num = 3 Then Data End) As Custom3
, Min(Case When Num = 4 Then Data End) As Custom4
...
From NumberedItems
Group By Id
在原始数据的一个严重问题是,有不是序列的指示器,因此系统无法知道给定ID的哪个项目应出现在Custom1列中,而不是Custom2列。在我上面的查询中,我随意按名称排序。