sql语句中行转列,以及列转行

行转列:

图1:      --------------------------------------------》》》》      图2:

             

 

 

 sql执行原理:根据id分组,然后select后面创建多次查询,生成列信息(利用case语句给分group by后的语句分类)

-- 行转列
select t.id, 
sum(case name when '仓库1' then t.num else NULL end) 仓库1,
sum(case name when '仓库2' then t.num else NULL end) 仓库2,
sum(case name when '仓库3' then t.num else NULL end) 仓库3
from  t
GROUP BY t.id;

 

列转行:

图1:      --------------------------------------------》》》》      图2:

 

                                     

第一步:sql执行原理:每个select语句只查某一个字段的值,创建多个查询,然后将多个select语句通过union链接,实现一条多列数据变成多行一列;比如一行 仓库1,仓库2,仓库3  最后变成多行

select p.id, '仓库1' name, p.`仓库1` num
from pr p
union
select p.id, '仓库2' name, p.`仓库2` num
from pr p
union
select p.id, '仓库3' name, p.`仓库3` num
from pr p 

执行结果:

 

 第二步:去掉为null的,即不存在行

select * from (
select p.id, '仓库1' name, p.`仓库1` num
from pr p
union
select p.id, '仓库2' name, p.`仓库2` num
from pr p
union
select p.id, '仓库3' name, p.`仓库3` num
from pr p ) T where T.num is not null
order by id, name

 

 

posted @ 2019-11-29 22:19  Java半路人生  阅读(2087)  评论(0)    收藏  举报