--具體的行列轉換並且進行行列資料統計
create table tmpa
( dept char(3) ,
sect char(3) ,
line char(3) ,
line_desc varchar(30) ,
title_code char(3) ,
title_desc varchar(30) ,
headcount int
);
-- 加入一些資料記錄
insert into tmpa values ('da' , 's1' , 'la' , 'line a ' , 't1' , 'title desc 1', 3 );
insert into tmpa values ('da' , 's1' , 'la' , 'line a ' , 't2' , 'title desc 2' , 3 );
insert into tmpa values ('da' , 's1' , 'lb' , 'line b ' , 't1' , 'title desc 1' , 3 );
insert into tmpa values ('da' , 's1' , 'lb' , 'line b ' , 't2' , 'title desc 2' , 3 );
insert into tmpa values ('da' , 's2' , 'la' , 'line a ' , 't1' , 'title desc 1' , 3 );
insert into tmpa values ('da' , 's2' , 'lb' , 'line b ' , 't1' , 'title desc 1' , 3 );
insert into tmpa values ('db' , 's1' , 'lb' , 'line b ' , 't1' , 'title desc 1' , 3 );
insert into tmpa values ('db' , 's2' , 'la' , 'line a ' , 't1' , 'title desc 1' , 3 );
insert into tmpa values ('db' , 's2' , 'lb' , 'line b ' , 't1' , 'title desc 1' , 3 );
insert into tmpa values ('dc' , 's1' , 'la' , 'line a ' , 't1' , 'title desc 1' , 3 );
insert into tmpa values ('dc' , 's2' , 'lb' , 'line b ' , 't1' , 'title desc 1' , 3);
select * from tmpa;
-- 行轉列一 行統計
select dept,decode(sect,'s1 ',sum(headcount),0) as s1,
decode(sect,'s2 ',sum(headcount),0) as s2,
sum(headcount) as 行合計
from tmpa
group by dept,sect,headcount;
-- 行轉列二 行統計
select dept,sum(decode(sect,'s1 ',headcount,0)) as s1,
sum(decode(sect,'s2 ',headcount,0)) as s2,
sum(headcount) as 行合計
from tmpa
group by dept,headcount;
-- 列統計
select dept,decode(sect,'s1 ',sum(to_number(headcount)),'0') as s1,
decode(sect,'s2 ',sum(to_number(headcount)),'0') as s2,
sum(to_number(headcount)) as 行合計
from tmpa
group by sect,rollup(dept,headcount);
-- 行列統計
select dept,sum(decode(sect,'s1 ',headcount,0)) as s1,
sum(decode(sect,'s2 ',headcount,0)) as s2,
sum(headcount) as 行合計
from tmpa
group by rollup(dept);
SQL進行行列轉換
假設現在有這樣一張表 create table dbo relconlist listid allint identity 1,1 not null listfkmainid varchar 20 collate chinese prc ci as not null listfkrelid varc...
sql進行行列轉換
1.分別求出孫悟空 豬八戒 沙僧的總打怪數 select sum kills from user1 a join user kills b on a.id b.user id where a.user name 孫悟空 select sum kills from user1 a join user ...
使用 case when進行行列轉換
固定列數的行列轉換,表結構為 轉換後 要求 建立表,源表,表名 student 只用一句sql 得到轉換結果。解答 方法一 通過生成臨時表的方式操作 select name sum yw as 語文 sum sx as 數學 sum wy as 英語 from select name case su...