我有一张这样的桌子:
ID Country InternetTLD CallingCode
1 Nicaragua .ni +505
2 USA .us +1
3 Spain .es +34
4 Germany .de +49
我需要这样的结果
1 2 3 4
Nicaragua USA Spain Germany
.ni .us .es .de
+505 +1 +34 +49
我尝试过使用数据透视,但是我只转换了一个列行,但是在这种情况下,对于第一个表中的每一行,它应该是结果表中的一列。
这是我的代码:
Create table #SampleTable (
ID int,
Country nvarchar(50),
InternetTLD nvarchar(50),
CallingCode nvarchar(50)
);
insert into #SampleTable (ID, Country, InternetTLD, CallingCode)
values
(1, 'Nicaragua', '.ni', '+505'),
(2, 'USA', '.us', '+505'),
(3, 'Spain', '.es', '+34'),
(4, 'Germany', '.de', '+49')
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
declare @PivotSelectColumnNames AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT @ColumnName= ISNULL(@ColumnName + ',','')
+ QUOTENAME(ID)
FROM (SELECT ID FROM #SampleTable ) AS ID
--Get distinct values of the PIVOT Column with isnull
SELECT @PivotSelectColumnNames
= ISNULL(@PivotSelectColumnNames + ',','')
+ 'ISNULL(' + QUOTENAME(ID) + ', 0) AS '
+ QUOTENAME(ID)
FROM (SELECT ID FROM #SampleTable ) AS ID
--Prepare the PIVOT query using the dynamic
SET @DynamicPivotQuery =
N'SELECT ' + @PivotSelectColumnNames + '
FROM #SampleTable
PIVOT(MAX(Country)
FOR ID IN (' + @ColumnName + ')) AS PVTTable '
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery
DROP TABLE #SampleTable
答案 0 :(得分:2)
您同时需要pivot
和unpivot
,因此,我将使用条件聚合&apply
来做到这一点:
select max(case when id = 1 then val end) as [1],
max(case when id = 2 then val end) as [2],
max(case when id = 3 then val end) as [3],
max(case when id = 4 then val end) as [4]
from table t cross apply
( values ('Country', Country, 1), ('InternetTLD', InternetTLD, 2), ('CallingCode', CallingCode, 3)
) tt(col, val)
group by col, seq
order by seq;