菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
135
0

数据人员Sql必会列转行

原创
05/13 14:22
阅读数 9458

列转行上一篇博客已经介绍过了。

下面介绍一下行转列的实现

假设我们有一个数据表:

CREATE TABLE row_to_line
(
  user_name character varying(30) NOT NULL, -- 学生名称
  yingyu integer, -- 得分
  yuwen integer,
  huaxue integer,
  wuli integer,  
  CONSTRAINT row_to_line_pkey PRIMARY KEY (user_name)
);

insert into row_to_line select 'liqiu', 80, 90, 90, 89;
insert into row_to_line select 'lingling', 89, 99, 100, 90;
insert into row_to_line select 'xingxing', 90, 94, 97, 99;

显示如下:

那么我们想要将它转化为一列列的如下结果输出:

那么如何做到哪?

方法一、简单可读性强:

select
  a.user_name,
  a.title,
  a.score
from 
(
  (select user_name, yingyu as "score", 'yingyu' as title from row_to_line)
  union (select user_name, yuwen as "score", 'yuwen' as title from row_to_line)
  union (select user_name, huaxue as "score", 'huaxue' as title from row_to_line)
  union (select user_name, wuli as "score", 'wuli' as title from row_to_line)
) a
order by a.user_name, a.title

方法二、快速

这是pg的专有方法

select * from tmp.dim_values_20170821 limit 10

 

 select lower(regexp_split_to_table(dim_values, ' ')) as dim_name, table_name,all_num from tmp.dim_values_20170821 where table_name = '景区统计表'

 

发表评论

0/200
135 点赞
0 评论
收藏
为你推荐 换一批