**:
--行轉列問題
--建立測試環境
create table test
(dates varchar(6),
empno varchar(5),
stype varchar(1),
amount int)
--插入資料
insert test select '200605', '02436', 'a', 5
union all select '200605', '02436', 'b', 3
union all select '200605', '02436', 'c', 3
union all select '200605', '02436', 'd', 2
union all select '200605', '02436', 'e', 9
union all select '200605', '02436', 'f', 7
union all select '200605', '02436', 'g', 6
union all select '200605', '02438', 'a', 7
union all select '200605', '02438', 'b', 8
union all select '200605', '02438', 'c', 0
union all select '200605', '02438', 'd', 3
union all select '200605', '02438', 'e', 4
union all select '200605', '02438', 'f', 5
union all select '200605', '02438', 'g', 1
go--測試
--如果stype固定,可以這麼寫
select
dates,
empno,
sum(case stype when 'a' then amount else 0 end) as a,
sum(case stype when 'b' then amount else 0 end) as b,
sum(case stype when 'c' then amount else 0 end) as c,
sum(case stype when 'd' then amount else 0 end) as d,
sum(case stype when 'e' then amount else 0 end) as e,
sum(case stype when 'f' then amount else 0 end) as f,
sum(case stype when 'g' then amount else 0 end) as g
from test
group by dates,empno
order by dates,empno
--如果stype不固定,用動態語句
declare @s varchar(1000)
set @s=''
select @s=@s+',sum(case stype when '''+stype+''' then amount else 0 end) as '+stype from (select distinct stype from test) a order by stype
set @s='select dates,empno'+@s+' from test group by dates,empno order by dates,empno'
exec(@s)
go--如果被轉置的是數字型別的話,應用下列語句
declare @s varchar(1000)
set @s='select dates,empno '
select @s=@s+',['+stype+']=sum(case when stype='''+stype+''' then amount else 0 end)'
from (select distinct stype from test) a order by stype
set @s=@s+' from test group by dates,empno'
exec(@s)
如果是列轉行的話直接union all就可以了
例如 :
city style color 46 48 50 52
長沙 s6mf01002 152 1 2 2 1
長沙 s6mf01002 201 1 2 2 1
上面到下面的樣子
city style color size qty
長沙 s6mf01002 152 46 1
長沙 s6mf01002 152 48 2
長沙 s6mf01002 152 50 2
長沙 s6mf01002 152 52 1
長沙 s6mf01002 201 46 1
長沙 s6mf01002 201 48 2
長沙 s6mf01002 201 50 2
長沙 s6mf01002 201 52 1
select city,style,color,[46] from test
union all
select city,style,color,[48] from test
union all
select city,style,color,[50] from test
union all
select city,style,color,[52] from test
就可以了
資料庫行轉列 列轉行的Sql語句總結
原資料 結果資料庫 通過for xml path把skill按 拼接在一起 纏繞 寄生 蛛網束縛 然後使用stuff函式把第乙個 符號去掉。sql code select a.into result from select 唐三 as name,纏繞 as skill union all selec...
oracle sql實現資料行轉列與列轉行
with tempas select 四川省 nation,成都市 第一,綿陽市 第二,德陽市 第三,宜賓市 第四 from dual union allselect 湖北省 nation,武漢市 第一,宜昌市 第二,襄陽市 第三,第四 from dual select nation,name,ti...
Sql server 中將資料行轉列列轉行(二)
第一步 建立臨時表結構 create table student 建立臨時表 stuname nvarchar 20 學生名稱 chinese int,math int,english int drop table student 刪除臨時表 select from student 查詢所有資料 i...