码迷,mamicode.com
首页 > 数据库 > 详细

sql中 行转列,列转行操作

时间:2020-07-15 15:24:55      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:生物   语文   char   ati   工程   国内   out   操作   sele   

CREATE TABLE [StudentScores]
(
[UserName] NVARCHAR(20), --学生姓名
[Subject] NVARCHAR(30), --科目
[Score] FLOAT, --成绩
)

INSERT INTO [StudentScores] SELECT ‘张三‘, ‘语文‘, 80
INSERT INTO [StudentScores] SELECT ‘张三‘, ‘数学‘, 90
INSERT INTO [StudentScores] SELECT ‘张三‘, ‘英语‘, 70
INSERT INTO [StudentScores] SELECT ‘张三‘, ‘生物‘, 85
INSERT INTO [StudentScores] SELECT ‘李四‘, ‘语文‘, 80
INSERT INTO [StudentScores] SELECT ‘李四‘, ‘数学‘, 92
INSERT INTO [StudentScores] SELECT ‘李四‘, ‘英语‘, 76
INSERT INTO [StudentScores] SELECT ‘李四‘, ‘生物‘, 88
INSERT INTO [StudentScores] SELECT ‘码农‘, ‘语文‘, 60
INSERT INTO [StudentScores] SELECT ‘码农‘, ‘数学‘, 82
INSERT INTO [StudentScores] SELECT ‘码农‘, ‘英语‘, 96
INSERT INTO [StudentScores] SELECT ‘码农‘, ‘生物‘, 78


select * from StudentScores
--

---行转列
select * from [StudentScores]
AS P
pivot
(
sum(Score) FOR
p.Subject IN ([语文],[数学],[英语],[生物])
) AS T

----
CREATE TABLE ProgrectDetail
(
ProgrectName NVARCHAR(20), --工程名称
OverseaSupply INT, --海外供应商供给数量
NativeSupply INT, --国内供应商供给数量
SouthSupply INT, --南方供应商供给数量
NorthSupply INT --北方供应商供给数量
)

INSERT INTO ProgrectDetail
SELECT ‘A‘, 100, 200, 50, 50
UNION ALL
SELECT ‘B‘, 200, 300, 150, 150
UNION ALL
SELECT ‘C‘, 159, 400, 20, 320

select * from ProgrectDetail

---列转行
select P.ProgrectName,P.Supplier,P.SupplyNum
from
(
select ProgrectName, OverseaSupply, NativeSupply,
SouthSupply, NorthSupply
from ProgrectDetail
)T
unpivot
(
SupplyNum FOR Supplier IN
(OverseaSupply, NativeSupply, SouthSupply, NorthSupply )
) P

sql中 行转列,列转行操作

标签:生物   语文   char   ati   工程   国内   out   操作   sele   

原文地址:https://www.cnblogs.com/yjm8023/p/13305186.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!