• 数据人员Sql必会——行转列


    今天被问到列转行的问题,竟然没有回答上来,回想自己也是数据开发人员,平时的积累真是不到位,下面总结一下列转行。

    假设咱们有一个学生得分数据表:student_score

    CREATE TABLE student_scores
    (
      user_name character varying(30) NOT NULL, -- 学生名称
      subject character varying(30) NOT NULL, -- 课程名称
      score integer, -- 得分
      CONSTRAINT student_scores_pkey PRIMARY KEY (user_name, subject)
    );
    COMMENT ON COLUMN student_scores.user_name IS '学生名称';
    COMMENT ON COLUMN student_scores.subject IS '课程名称';
    COMMENT ON COLUMN student_scores.score IS '得分';

    是postgresql的语法,就四个字段,下面是数据库内容:

    那么我希望把这些数据用另外的一种方式展现,比如:

    那么如何使用sql实现哪?下面我贴出来代码:

    第一种办法,逻辑简单 左关联:

    SELECT 
      a.user_name,
      b.score as "语文",
      c.score as "数学",
      d.score as "英语",
      e.score as "生物"
    FROM (select distinct user_name from student_scores) a
    left join (select score, user_name FROM student_scores where subject = '语文') b on b.user_name=a.user_name
    left join (select score, user_name FROM student_scores where subject = '数学') c on c.user_name=a.user_name
    left join (select score, user_name FROM student_scores where subject = '英语') d on d.user_name=a.user_name
    left join (select score, user_name FROM student_scores where subject = '生物') e on e.user_name=a.user_name

    第二种方法,必然好了一些:

    SELECT 
          user_name, 
          MAX(CASE subject WHEN '语文' THEN Score ELSE 0 END) AS "语文",
          MAX(CASE subject WHEN '数学' THEN Score ELSE 0 END) AS "数学",
          MAX(CASE subject WHEN '英语' THEN Score ELSE 0 END) AS "英语",
          MAX(CASE subject WHEN '生物' THEN Score ELSE 0 END) AS "生物"
    FROM student_scores
    GROUP BY user_name
  • 相关阅读:
    领导者是梦想家,却不能只是梦想家
    8i查询DBA_FREE_SPACE视图极慢的问题
    11g 新特性IGNORE_ROW_ON_DUPKEY_INDEX提示
    ORA00600:[qctcte1]内部错误一例
    利用FORCE_MATCHING_SIGNATURE捕获非绑定变量SQL
    Does DB Time include wait on cpu queue time?
    对于OCM考试的几点意见和建议
    rman hang on SQL*Net message from client
    ddl操作是否会产生undo?
    ORA07445: [__lwp_kill()+8] [SIGIOT]错误一例
  • 原文地址:https://www.cnblogs.com/liqiu/p/4925515.html
Copyright © 2020-2023  润新知