列轉行上一篇博客已經介紹過了。spa
下面介紹一下行轉列的實現code
假設咱們有一個數據表:regexp
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;
顯示以下:blog
那麼咱們想要將它轉化爲一列列的以下結果輸出:博客
那麼如何作到哪?it
方法1、簡單可讀性強:io
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
方法2、快速table
這是pg的專有方法class
select * from tmp.dim_values_20170821 limit 10select
select lower(regexp_split_to_table(dim_values, ' ')) as dim_name, table_name,all_num from tmp.dim_values_20170821 where table_name = '景區統計表'