sql 行转列 列转行

1、行转列一般通过case when语句来实现。

create table studentscores(
    username varchar(20),
    subject varchar(30),
    score float
);
insert into studentscores select 'Nick','语文',80;
insert into studentscores select 'Nick','数学',90;
insert into studentscores select 'Nick','英语',70;
insert into studentscores select 'Nick','生物',85;
insert into studentscores select 'Kent','语文',80;
insert into studentscores select 'Kent','数学',90;
insert into studentscores select 'Kent','英语',70;
insert into studentscores select 'Kent','生物',85;

select username,
 max(case subject when '语文' then score else 0 end) as '语文',
 max(case subject when '数学' then score else 0 end) as '数学',
 max(case subject when '英语' then score else 0 end) as '英语',
 max(case subject when '生物' then score else 0 end) as '生物'
from studentscores
GROUP BY username;

create table inpours
(
    id int primary key AUTO_INCREMENT,
    username varchar(20),
    createtime datetime,
    paytype varchar(20),
    money decimal,
    issuccess bit
);

insert into inpours select 1,'张三','2010-05-01','支付宝',50,1;
insert into inpours select 2,'张三','2010-06-14','支付宝',50,1;
insert into inpours select 3,'张三','2010-06-14','手机短信',100,1;
insert into inpours select 4,'李四','2010-06-14','手机短信',100,1;
insert into inpours select 5,'李四','2010-07-14','支付宝',100,1;
insert into inpours select 6,'王五','2010-07-14','工商银行卡',100,1;
insert into inpours select 7,'赵六','2010-07-14','建设银行卡',100,1;

select createtime,
 case paytype when '支付宝' then sum(money) else 0 end as '支付宝',
 case paytype when '手机短信' then sum(money) else 0 end as '手机短信',
 case paytype when '工商银行卡' then sum(money) else 0 end as '工商银行卡',
 case paytype when '建设银行卡' then sum(money) else 0 end as '建设银行卡'
from inpours
group by createtime,paytype;

2、列转行,主要是通过UNION ALL,MAX来实现

create table progrectdetail(
    progrectname varchar(20),
    overseasupply int,
    nativesupply int,
    southsupply int,
    northsupply int
);

insert into progrectdetail select 'A',100,200,50,50
union ALL
select 'B',200,300,150,150
union ALL
select 'C',159,400,20,320
union ALL
select 'D',250,30,15,15;

select progrectname,'OverseaSupply' as supplier,
max(overseasupply) as 'supplynum'
from progrectdetail
GROUP BY progrectname
union ALL
select progrectname,'nativesupply' as supplier,
max(nativesupply) as 'supplynum'
from progrectdetail
GROUP BY progrectname
union ALL
select progrectname,'southsupply' as supplier,
max(southsupply) as 'supplynum'
from progrectdetail
GROUP BY progrectname
union ALL
select progrectname,'northsupply' as supplier,
max(northsupply) as 'supplynum'
from progrectdetail
GROUP BY progrectname;

猜你喜欢

转载自www.cnblogs.com/npng09/p/10886765.html