SQL語句查詢結果由行變為列

2021-04-15 22:01:38 字數 1240 閱讀 7585

q: 

用sql語句,把表中的資料由行變為列.

查詢前:

id 姓名 科目 分數

1 張三 語文 65

2 張三 數學 85

3 張三 外語 75

4 李四 語文 90

5 李四 數學 60

6 李四 外語 50

查詢後:

姓名 語文 數學 外語

李四 90 60 50

張三 65 85 75 a:

1.先建表.

create table scoretable

(id int not null primary key,

name varchar(50),

subject varchar(50),

score int null

); 2.新增資料.

insert into scoretable(id, name, subject, score) values(1, '張三', '語文', 70);

insert into scoretable(id, name, subject, score) values(2, '張三', '數學', 85);

insert into scoretable(id, name, subject, score) values(3, '張三', '外語', 75);

insert into scoretable(id, name, subject, score) values(4, '李四', '語文', 90);

insert into scoretable(id, name, subject, score) values(5, '李四', '數學', 60);

insert into scoretable(id, name, subject, score) values(6, '李四', '外語', 50);

3.用sql實現.

select name as '姓名',

sum(case subject when '語文' then score else 0 end) as '語文',

sum(case subject when '數學' then score else 0 end) as '數學',

sum(case subject when '外語' then score else 0 end) as '外語'

from scoretable

group by name

這就做完了.主要就是這個sql語句.其實很簡單. 

讓查詢資料由行變成列

有這樣兩個資料表 wuzi table 物資編碼 id 顏色編號 color id 數量 acount 1111 1 10 2222 2 20 1111 1 20 3333 3 5 1111 3 10 yanse table 顏色編號 color id 顏色名稱 color 1 紅色2 蘭色3 綠色...

Oracle行轉換列SQL語句

select fmonth,sum decode factionid,1,fcount,0 as factionid1,sum decode factionid,2,fcount,0 as factionid2 from select fmonth,factionid,count as fcount...

用sql語句要求行變列,列變行

create table tb 姓名 varchar 10 課程 varchar 10 分數 int insert into tb values 張三 語文 74 insert into tb values 張三 數學 83 insert into tb values 張三 物理 93 insert...