Pivot\Unpivot 问题?
Pivot\Unpivot issues?
我有以下数据
Col1, Col2, Col3, Col4, Col5
1, P, W, M, adhfggh
1, P, W, M, fdasdfd
1, P, W, M, retretre
所以,我想要这个
Col1, Col2, Col3, Col4, ColA, ColB, ColC
1, P, W, M, adhfggh, fdasdfd, retretre
我应该试试这样的东西,但不确定在括号中放什么
select Col1, Col2, Col3, Col4, Col5 from tableA
Unpivot
( Col1, Col2, Col3, Col4 for Col5 in (, , ) ) as UnPvt
感谢您的帮助。
您没有指定您使用的 SQL 版本,所以这是 T-SQL 并且可以在 2008 年后的任何 SQL 服务器上运行。
这个动态枢轴是 altered from this answer & will format to your requirements. You might also wish to look into the STUFF 函数
CREATE TABLE #T
( Col1 int
,Col2 [nchar](3)
,Col3 [nchar](3)
,Col4 [nchar](3)
,Col5 [nchar](10)
)
Insert Into #T
Values
(1,'P','W','M','adhfggh')
,(1,'P','W','M','fdasdfd')
,(1,'P','W','M','retretre');
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.Col5)
FROM #T c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT Col1,Col2,Col3,Col4, ' + @cols + ' from
(
select Col1,
Col2,
Col3,
Col4,
Col5
from #T
) x
pivot
(
max(Col5)
for Col5 in (' + @cols + ')
) p '
execute(@query)
drop table #T
我有以下数据
Col1, Col2, Col3, Col4, Col5
1, P, W, M, adhfggh
1, P, W, M, fdasdfd
1, P, W, M, retretre
所以,我想要这个
Col1, Col2, Col3, Col4, ColA, ColB, ColC
1, P, W, M, adhfggh, fdasdfd, retretre
我应该试试这样的东西,但不确定在括号中放什么
select Col1, Col2, Col3, Col4, Col5 from tableA
Unpivot
( Col1, Col2, Col3, Col4 for Col5 in (, , ) ) as UnPvt
感谢您的帮助。
您没有指定您使用的 SQL 版本,所以这是 T-SQL 并且可以在 2008 年后的任何 SQL 服务器上运行。
这个动态枢轴是 altered from this answer & will format to your requirements. You might also wish to look into the STUFF 函数
CREATE TABLE #T
( Col1 int
,Col2 [nchar](3)
,Col3 [nchar](3)
,Col4 [nchar](3)
,Col5 [nchar](10)
)
Insert Into #T
Values
(1,'P','W','M','adhfggh')
,(1,'P','W','M','fdasdfd')
,(1,'P','W','M','retretre');
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.Col5)
FROM #T c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT Col1,Col2,Col3,Col4, ' + @cols + ' from
(
select Col1,
Col2,
Col3,
Col4,
Col5
from #T
) x
pivot
(
max(Col5)
for Col5 in (' + @cols + ')
) p '
execute(@query)
drop table #T