數據人員Sql必會——行轉列

今天被問到列轉行的問題,居然沒有回答上來,回想本身也是數據開發人員,平時的積累真是不到位,下面總結一下列轉行。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的語法,就四個字段,下面是數據庫內容:post

那麼我但願把這些數據用另外的一種方式展示,好比:spa

那麼如何使用sql實現哪?下面我貼出來代碼:postgresql

第一種辦法,邏輯簡單 左關聯:code

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

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

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
相關文章
相關標籤/搜索