如何创建数据成为列

时间:2018-11-13 04:19:02

标签: sql sql-server tsql

我们如何针对这种情况编写SQL查询? 该表的结构为;

| Room | BLOK | DATA |
|   1  |   A  |  12  |
|   2  |   A  |  13  |
|   1  |   B  |  14  |
|   3  |   B  |  15  |

预期输出:


| Room |   A  |  B   |
|   1  |   12 |  14  |
|   2  |   13 | null |
|   3  |  null|  15  |

2 个答案:

答案 0 :(得分:2)

您可以尝试使用条件聚合

DEMO

select room, max(case when BLOK='A' then DATA end) as A,
max(case when BLOK='B' then DATA end) as B
from tablename
group by room

或尝试使用PIVOT

select room,pv.* from 
tablename
pivot(max(DATA) for BLOK in ([A],[B])) pv

输出:

Room    A   B
1      12   14
2      13   
3           15

对于动态数据透视

declare @sql varchar(max)='',@col_list varchar(8000)=''

set @col_list = (select distinct quotename([BLOK])+',' from tablename
for xml path(''))

set @col_list = left (@col_list,len(@col_list)-1)

set @sql = 'select Room,'+@col_list+' from
tablename
pivot (max([DATA]) for [BLOK] in ('+@col_list+'))pv'

exec(@sql)

FIDDLE FOR DYNAMIC PIVOT

答案 1 :(得分:1)

您可以尝试PIVOT

尝试在下面查询表和数据以获得所需结果。

查询:

select [Room],
        [A] as A,
        [B] as B
from
--Step2 get the actual data
(
select Room,
        Block,
        Data
        From SOPivot
) as PivotData

--step3 pivot function
pivot
(
sum(Data) for Block in 
(A,B))as Pivoting
order by Room