目标是动态地透视数据,然后动态地取消透视它。
我遇到一个错误,说*.ism
我之所以这样假设,是因为变量Invalid ControlNo
包含ControlNo列。
但是我该如何解决?我绝对需要那个ControlNo。
@colsUnpivot
输出应如下所示:
答案 0 :(得分:1)
我假设您的样本输出是一个样本,并且您排除了其他控制编号。如果是这样,更改where
中的stuff
子句将从unpivot
组中删除该列,并为您提供所需的结果。您不能返回要旋转或不旋转的列。
IF OBJECT_ID('tempdb..##A') IS NOT NULL DROP TABLE ##A
IF OBJECT_ID('tempdb..#table1') IS NOT NULL DROP TABLE #table1
Create table #Table1 ( ControlNo INT, Bound INT, Declined INT, Rated INT, Quoted INT, QuoteStatus VARCHAR(50) )
INSERT INTO #Table1 (ControlNo, Bound, Declined, Rated, Quoted, QuoteStatus)
VALUES (1111,1,0,1,1,'Lost'),
(2222,0,1,0,1,'No Action'),
(3333,1,1,0,0,NULL),
(4444,1,0,0,1,'Lost'),
(5555,0,1,1,1,'No Action')
DECLARE @columns AS NVARCHAR(MAX),
@finalquery AS NVARCHAR(MAX);
SET @columns = STUFF((SELECT distinct ',' + QUOTENAME(QuoteStatus) FROM #Table1 FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')
--PRINT @columns
set @finalquery = '
select p.controlno,
p.Bound,
p.Declined,
p.Rated,
p.Quoted,' + @columns + '
into ##A
from ( select *
from #Table1
)a
pivot
(
COUNT(QuoteStatus)
for QuoteStatus IN (' + @columns + ')
)p '
exec(@finalquery)
--SELECT *
--FROM ##a
DECLARE @colsUnpivot AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @colsUnpivot
= stuff((select ','+quotename(C.name)
FROM tempdb.sys.columns c
--notice i remove controlno here...
WHERE c.object_id = OBJECT_ID('tempdb..##A') and c.name <> 'controlno'
for xml path('')), 1, 1, '')
--PRINT @colsUnpivot
set @query
= 'select Controlno, Counts, Status
from ##A
unpivot
(
Counts
for Status in ('+ @colsunpivot +')
) u'
exec sp_executesql @query;
要获得准确的输出,只需在set @query
中添加where子句。
set @query
= 'select Controlno, Counts, Status
from ##A
unpivot
(
Counts
for Status in ('+ @colsunpivot +')
) u
where controlno = 1111'