SQL Server数据行转列案例实践

数据库某表行转列案例实践

--第一步,创建测试表[StudentsScore]及测试数据


CREATE TABLE [dbo].[StudentsScore](
 [Student] [varchar](10) NOT NULL,
 [Subject] [varchar](10) NOT NULL,
 [Score] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
INSERT [dbo].[StudentsScore] ([Student], [Subject], [Score]) VALUES (N'学生A', N'中文', 80)
INSERT [dbo].[StudentsScore] ([Student], [Subject], [Score]) VALUES (N'学生A', N'数学', 90)
INSERT [dbo].[StudentsScore] ([Student], [Subject], [Score]) VALUES (N'学生A', N'英语', 95)
INSERT [dbo].[StudentsScore] ([Student], [Subject], [Score]) VALUES (N'学生B', N'中文', 89)
INSERT [dbo].[StudentsScore] ([Student], [Subject], [Score]) VALUES (N'学生B', N'数学', 86)
INSERT [dbo].[StudentsScore] ([Student], [Subject], [Score]) VALUES (N'学生B', N'英语', 90)
INSERT [dbo].[StudentsScore] ([Student], [Subject], [Score]) VALUES (N'学生C', N'中文', 75)
INSERT [dbo].[StudentsScore] ([Student], [Subject], [Score]) VALUES (N'学生C', N'数学', 86)
INSERT [dbo].[StudentsScore] ([Student], [Subject], [Score]) VALUES (N'学生C', N'英语', 90)
INSERT [dbo].[StudentsScore] ([Student], [Subject], [Score]) VALUES (N'学生D', N'中文', 86)
INSERT [dbo].[StudentsScore] ([Student], [Subject], [Score]) VALUES (N'学生D', N'数学', 98)
INSERT [dbo].[StudentsScore] ([Student], [Subject], [Score]) VALUES (N'学生D', N'英语', 85)

实现效果如下


--第二步,用两种方法实现行转列

 

--方法一:利用sql2005中的新功能 PIVOT(可以将数据值转换为数据列)
select A.*,B.[总分],B.[平均分]
from
(select Student,[中文],[数学],[英语]
from
(select * from StudentsScore) as PS
PIVOT
(max(score)
for [Subject] in([中文],[数学],[英语])
)as pivotTable) A,
(select Student,SUM(score)[总分],cast(AVG(score*1.0)as decimal(18,2))[平均分] from StudentsScore group by Student) B where A.Student=B.Student

--方法二:用传统的case方法
select Student,
max(case [subject] when '中文' then Score else 0 end) [中文],
max(case [subject] when '数学' then Score else 0 end) [数学],
max(case [subject] when '英语' then Score else 0 end) [英语],
SUM(Score)[总分],
cast(AVG(score*1.0)as decimal(18,2))[平均分]
from StudentsScore group by Student

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值