我有一个看起来如下的表,想要转动它
Acct_ID Dec_DT Dec_rsn 1 2013-04-01 00:00:00.000 k 1 2013-01-01 00:00:00.000 x 1 2013-01-02 00:00:00.000 y 1 2013-10-02 00:00:00.000 z 2 2013-01-01 00:00:00.000 x 2 2013-01-01 00:00:00.000 y 2 2013-11-01 00:00:00.000 x 3 2013-12-01 00:00:00.000 z 4 2013-01-01 00:00:00.000 z 5 2013-11-01 00:00:00.000 y 5 2013-02-01 00:00:00.000 z 6 2013-03-01 00:00:00.000 x 1 2013-05-21 00:00:00.000 x
我有以下代码但不能正常工作....
DECLARE
@cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SET @cols =
STUFF((SELECT distinct ',' + QUOTENAME(ROW_NUMBER()OVER(PARTITION BY ACCT_ID ORDER BY Dec_dt DESC)) as DecRsn
FROM #test c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'Select Acct_ID, ' + @cols + ' from
(
SELECT
Acct_ID,
Dec_DT,
Dec_rsn
from #test
)x
pivot
(
max(Dec_DT)
for Dec_rsn in (' + @cols + ')
)p '
execute(@query)
答案 0 :(得分:1)
使用以下查询来解决您的问题:
DECLARE
@cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SET @cols =
STUFF((SELECT distinct ',' + QUOTENAME(ROW_NUMBER()OVER(PARTITION BY Acct_ID ORDER BY Dec_dt DESC)) as DecRsn
FROM tbl c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'Select Dec_rsn,' + @cols + ' from
(
SELECT
Acct_ID,
Dec_DT,
Dec_rsn
from #test) x
pivot
(
max(Dec_DT)
for Acct_ID in (' + @cols + ')
)p '
print @query
execute(@query)
答案 1 :(得分:0)
declare @stmt nvarchar(max)
select @stmt = isnull(@stmt + ', ', '') + Dec_rsn
from (select distinct Dec_rsn from Table1) as a
select @stmt = '
select Acct_ID, ' + @stmt + '
from Table1 as x
pivot (
max(Dec_DT) for Dec_rsn in (' + @stmt + ')
) as p'
exec sp_executesql @stmt = @stmt
<强> sql fiddle demo 强>
declare @stmt nvarchar(max)
select @stmt = isnull(@stmt + ', ', '') + Dec_rsn
from (select distinct 'Dec_rsn' + cast(dense_rank() over(order by Dec_rsn) as nvarchar(max)) as Dec_rsn from Table1) as a
select @stmt = '
select Acct_ID, ' + @stmt + '
from (
select
Acct_ID, Dec_DT,
''Dec_rsn'' + cast(dense_rank() over(order by Dec_rsn) as nvarchar(max)) as Dec_rsn
from Table1
) as a
pivot (
max(Dec_DT) for Dec_rsn in (' + @stmt + ')
) as p'
exec sp_executesql @stmt = @stmt
<强> sql fiddle demo 强>
declare @stmt nvarchar(max)
select @stmt = isnull(@stmt + ', ', '') + Dec_rsn
from (select distinct 'Dec_rsn' + cast(row_number() over(partition by Acct_ID order by Dec_DT) as nvarchar(max)) as Dec_rsn from Table1) as a
select @stmt = '
select Acct_ID, ' + @stmt + '
from (
select
Acct_ID, Dec_rsn,
''Dec_rsn'' + cast(row_number() over(partition by Acct_ID order by Dec_DT) as nvarchar(max)) as rn
from Table1
) as a
pivot (
max(Dec_rsn) for rn in (' + @stmt + ')
) as p'
exec sp_executesql @stmt = @stmt
<强> sql fiddle demo 强>