我有一张带有“代码”和“描述”列的表。行应动态转置为列 例如
Create Table #table(Code Varchar(15), Code_Desc Varchar(30))
Insert Into #table Values('T01', 'Desc1')
Insert Into #table Values('T02', 'Desc2')
Insert Into #table Values('T03', 'Desc3')
Insert Into #table Values('T04', 'Desc4')
Select * from #table
Code Code_Desc
T01 Desc1
T02 Desc2
T03 Desc3
T04 Desc4
预期输出为:
Code T01 T02 T03 T04
Code_Desc Desc1 Desc2 Desc3 Desc4
谢谢
答案 0 :(得分:1)
您可以在下面尝试
select 'Code_Desc' as code,[T01], [T02], [T03], [T04] from #table
pivot(max(Code_Desc) for code in ([T01], [T02], [T03], [T04]))pv
输出:
code T01 T02 T03 T04
Code_Desc Desc1 Desc2 Desc3 Desc4
对于动态数据透视,您可以尝试以下操作:
declare @sql varchar(max)='',@col_list varchar(8000)=''
set @col_list = (select distinct quotename([Code])+',' from #table
for xml path(''))
set @col_list = left (@col_list,len(@col_list)-1)
set @sql = 'select '+@col_list+' from
#table
pivot (max([Code_Desc]) for [Code] in ('+@col_list+'))pv'
exec(@sql)
答案 1 :(得分:0)
如果不进行汇总,就无法实现PIVOT。
CREATE TABLE #table1
(
TEST_NAME VARCHAR(10),
SBNO VARCHAR(10),
VAL VARCHAR(10)
);
INSERT INTO #table1 (TEST_NAME, SBNO, VAL)
VALUES ('Test1' ,'1', '0.304'),
('Test1' ,'2', '0.31'),
('Test1' ,'3', '0.306'),
('Test2' ,'1', '2.3'),
('Test2' ,'2', '2.5'),
('Test2' ,'3', '2.4'),
('Test3' ,'1', 'PASS'),
('Test3' ,'2', 'PASS')
WITH T AS
(
SELECT SBNO, VAL, TEST_NAME
FROM #table1
)
SELECT *
FROM T
PIVOT (MAX(VAL) FOR TEST_NAME IN([Test1], [Test2], [Test3])) P
答案 2 :(得分:0)
不使用聚合函数进行透视
Create Table #table(Code Varchar(15), Code_Desc Varchar(30))
Insert Into #table Values('T01', 'Desc1')
Insert Into #table Values('T02', 'Desc2')
Insert Into #table Values('T03', 'Desc3')
Insert Into #table Values('T04', 'Desc4')
SELECT DISTINCT dt.Code,T01,T02,T03,T04
FROM #table
CROSS APPLY ( VALUES ('Code_Desc','Desc1','Desc2','Desc3','Desc4' ) ) dt (Code,T01,T02,T03,T04)
动态Sql方法
DECLARE @SQL Nvarchar(max)
,@Columns nvarchar(max)
,@Columns2 nvarchar(max)
,@Columns3 nvarchar(max)
SELECT @Columns =STUFF((SELECT ', '+''''+ Code_Desc+'''' FROM #table FOR XML PATH ('')),1,1,'')
SELECT @Columns2=STUFF((SELECT ', '+ Code FROM #table FOR XML PATH ('')),1,1,'')
SELECT @Columns3=STUFF((SELECT ', '+ 'dt.'+QUOTENAME(Code) FROM #table FOR XML PATH ('')),1,1,'')
SET @SQL='SELECT DISTINCT dt.[Code],'+@Columns3+'
FROM #table
CROSS APPLY (VALUES(''Code_Desc'','+@Columns+'))'+CHAR(13)+CHAR(10)+' dt( Code,'+@Columns2+')'
PRINT @SQL
EXEC (@SQL)
结果
Code T01 T02 T03 T04
-------------------------------------------
Code_Desc Desc1 Desc2 Desc3 Desc4