將 橫表 轉為 直表,如 class 有很多 type 每個 type 僅有 一個值(a1),現在想列出 每個class type 的 a1 值 (這是有所限制的,必須有特定的資料才能轉)
------------------------------------------------------------------------
print '建範例表 #tmp1'
select * into #tmp1
from (
select '1' no, '101' class, 'A' type,'66' a1,'88' a2,'55' a3
union select '2','101','B','77','88','77'
union select '3','101','C','88','78','65'
union select '4','102','A','66','50','56'
union select '5','102','C','77','78','67'
) a
go
print '顯示 #tmp1 '
select * from #tmp1
go
------------------------------------------------------------------------
print '依 type 直列數值 a1, a2, a3'
select class,type,a1 from #tmp1
select class
, max(case when type='A' then a1 else '' end) A
, max(case when type='B' then a1 else '' end) B
, max(case when type='C' then a1 else '' end) C
from #tmp1
group by class
沒有留言:
張貼留言