仅对所有数据进行透视列更改

时间:2017-10-07 07:00:14

标签: sql sql-server database tsql

我需要将SQL表转换为预期的o / p。

当前表格

id   status month
100  P      August
101  D      August
101  P      August
102  P      August
102  P      sept

预期o / p:

id   August Sept
100  P      NULL 
101  D      NULL
101  P      NULL
102  P      P

我需要所有记录。

3 个答案:

答案 0 :(得分:1)

使用Pivot。

select *  FROM (
SELECT id  , status, month,
ROW_NUMBER() over( partition by id,month order by id,status )rnk
FROM #tableName w 

) up
PIVOT (  max(status) FOR month IN ([August],[Sept])) AS pvt

答案 1 :(得分:0)

如果您的[月]是动态的,可以使用动态SQL:

declare @sql nvarchar(max)= '';

-- gathering column names in @sql
select @sql = @sql + ',[' + [month] + ']'
from yourTable
group by [month];

-- creating query text with gathered name of columns
set @sql = 'select id'+@sql+' from (select *, rank() over (partition by id,[month] order by id,[status])rnk from yourTable) w pivot(max([status]) for [month] in ('+
    stuff(@sql,1,1,'')+')) as pvt';

-- executing query
EXEC(@sql);

使用XQuery的另一种方法是实现它:

;with tx as (
    select id, 
        -- generate an xml field with `for xml`
        cast((select 
                -- using `case` to separate columns per value of `[mont]`
                case when [month] = 'August' then ti.[status] end [August],
                case when [month] = 'sept' then ti.[status] end [sept]
            from t ti       
            where t.id = ti.id      
            for xml path('')) as xml) x
    from yourTable
    group by id
)
select id, 
    -- get value of node
    txAugust.c.value('.', 'varchar(10)') [August], 
    txsept.c.value('.', 'varchar(10)') [sept]
from tx
-- using nodes of `[August]` 
outer apply
tx.x.nodes('./August') txAugust(c)
-- using nodes of `[sept]`
outer apply
tx.x.nodes('./sept') txsept(c);

答案 2 :(得分:0)

另一种解决方案。

SELECT *  FROM
    (SELECT CONCAT(id,  status) UNQ, * FROM @MyTable) SRC
    PIVOT ( MAX(status) FOR [month] IN ([August],[Sept])) PVT

结果:

id          August     Sept
----------- ---------- ----------
100         P          NULL
101         D          NULL
101         P          NULL
102         P          P