SQL实现行转列和列转行简单例子

一、行转列

-- oracle创建表
create table score
(
    id  NUMBER(8) not null,
    subject    VARCHAR2(20),
    score NUMBER(10)
);
原表结构:
| ID | SUBJECT | SCORE |
| 1 | 数学 | 100 |
| 2 | 数学 | 60 |
| 1 | 语文 | 100 |
| 2 | 语文 | 60 |


-- 1.经典的sum(max也可以)+if(case when也可以)+group by
select id,
       sum(case subject
           when 'math' then score
        else null end) math,
       sum(case subject
           when 'chinese' then score
           else null end) chinese
from score group by id;

-- 2.连接
select a.id, a.score math, b.score chinese
from (
         select * from score where subject = 'math') a
         left join (select * from score where subject = 'chinese') b
                   on a.id = b.id;
                   
-- 3.使用natural join 两表使用自然连接时(如table1:id,math ~ table2:id,chinese => table3:id,math,chinese)
-- 会根据同名列连接,如同名例字段值也相同,会合并程一行。如果没有同名列,则进行笛卡尔积。
select *
from (
         select id, score math from score where subject = 'math') a
         natural join (select id, score chinese from score where subject = 'chinese') b;

-- 4.union all + 分组


结果:
| ID | MATH | CHINESE |
| 1 | 100 | 100 |
| 2 | 60 | 60 |

二、列转行

原表结构:
| ID | MATH | CHINESE |
| 1 | 100 | 100 |
| 2 | 60 | 60 |

-- 列转行(把上面的行转列结果直接拿过来,用列转行复原)
-- 1. union all
select id, '数学' subject, math score
from (select *
      from (
               select id, score math from score where subject = 'math') a
               natural join (select id, score chinese from score where subject = 'chinese') b)
union all
select id, '语文' subject, chinese score
from (select *
      from (
               select id, score math from score where subject = 'math') a
               natural join (select id, score chinese from score where subject = 'chinese') b)
;

结果:
| ID | SUBJECT | SCORE |
| 1 | 数学 | 100 |
| 2 | 数学 | 60 |
| 1 | 语文 | 100 |
| 2 | 语文 | 60 |
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值