zoukankan      html  css  js  c++  java
  • 数据人员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;

    显示如下:

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

    那么如何做到哪?

    方法一、简单可读性强:

    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 = '景区统计表'

  • 相关阅读:
    洛谷P1169 [ZJOI2007]棋盘制作
    洛谷P4147 玉蟾宫
    洛谷P3068 [USACO13JAN]Party Invitations S
    洛谷P3594 [POI2015]WIL-Wilcze doły
    洛谷P2564 [SCOI2009]生日礼物
    洛谷P4296 [AHOI2007]密码箱
    洛谷P2421 [NOI2002]荒岛野人
    洛谷P3990 [SHOI2013]超级跳马
    MySQL 默认引擎 默认编码
    Python 换源
  • 原文地址:https://www.cnblogs.com/liqiu/p/4927405.html
Copyright © 2011-2022 走看看