数据人员Sql必会列转行

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

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

假设我们有一个数据表:

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必会列转行_第1张图片

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

数据人员Sql必会列转行_第2张图片

那么如何做到哪?

方法一、简单可读性强:

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

方法二、快速

 

你可能感兴趣的:(数据人员Sql必会列转行)