首页 技术 正文
技术 2022年11月15日
0 收藏 911 点赞 4,488 浏览 919 个字

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

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

假设我们有一个数据表:

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;

显示如下:

数据人员Sql必会列转行

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

数据人员Sql必会列转行

那么如何做到哪?

方法一、简单可读性强:

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

数据人员Sql必会列转行

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

数据人员Sql必会列转行

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,491
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,492
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,293