1. 程式人生 > >sqlserver 行轉列(轉)

sqlserver 行轉列(轉)

微軟 技術 all drop 記錄 記錄拆分 div student 數學

1、行轉列 微軟官方的圖:

技術分享圖片

方法二

技術分享圖片

-- 行轉列

DROP TABLE studentB;

CREATE TABLE studentB (
姓名 varchar(10),
語文 varchar(10),
數學 varchar(10),
物理 varchar(10)
);

INSERT INTO studentB
VALUES (‘張三‘, 75, 83, 96),
(‘李四‘, 74, 84, 95);

SELECT *
FROM (
SELECT 姓名, ‘語文‘ AS 科目, 語文 AS 分數
FROM studentB
UNION ALL
SELECT 姓名, ‘數學‘ AS 科目, 數學 AS 分數
FROM studentB
UNION ALL
SELECT 姓名, ‘物理‘ AS 科目, 物理 AS 分數
FROM studentB
) a

2: 列轉行

怎麽把一條記錄拆分成幾條記錄?
User No. A B C
1 1 21 34 24
1 2 42 25 16

RESULT:

User No. Type Num
1 1 A 21
1 1 B 34
1 1 C 24
1 2 A 42
1 2 B 25
1 2 C 16


declare @t table(usser int ,no int ,a int,b int, c int)
insert into @t select 1,1,21,34,24
union all select 1,2,42,25,16

SELECT usser,no,Type=attribute, Num=value
FROM @t
UNPIVOT
(
value FOR attribute IN([a], [b], [c])
) AS UPV

--結果
/*

usser no Type num
---- --- -------- --------
1 1 a 21
1 1 b 34
1 1 c 24
1 2 a 42
1 2 b 25
1 2 c 16
*/

方法二

技術分享圖片

-- 列傳行
drop table studentA;
create table studentA (name varchar(10) ,subject varchar(10) ,score int) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert into studentA values (‘張三‘,‘語文‘,75),(‘張三‘,‘數學‘,83),(‘張三‘,‘物理‘,96);
insert into studentA values (‘李四‘,‘語文‘,74),(‘李四‘,‘數學‘,84),(‘李四‘,‘物理‘,95);

select name 姓名,
max(case subject when ‘語文‘ then score end) 語文,
max(case subject when ‘數學‘ then score end) 數學,
max(case subject when ‘物理‘ then score end) 物理
from studentA
group by name



sqlserver 行轉列(轉)