请教一句sql

Jill_Yao 2013-01-15 11:03:32
有表类似 (课程分数须累加)
学号 课程 分数
1 A 90
2 B 30
.
.
.

需要形成统计表格如下
学号 课程A 课程B 课程C 课程D
1 90 50 60 70
2 80 55 78 34
.
.
.

怎么写效率高呢

我只想出
select id,
(select sum(fenshu) from table where class='A' and b where b.id table.id) A,
(select sum(fenshu) from table where class='B' and b where b.id table.id) B,
(select sum(fenshu) from table where class='C' and b where b.id table.id) C
from table;
可是这样效率极低。




...全文
234 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
Jill_Yao 2013-01-15
  • 打赏
  • 举报
回复
多谢大家帮忙,已经搞定了
美到心痛 2013-01-15
  • 打赏
  • 举报
回复
这是2000以上的做法。 2005以上可以用pivot.自己找资料。
發糞塗牆 2013-01-15
  • 打赏
  • 举报
回复
你这个要用动态吧
----------------------------------------------------------------
-- Author  :DBA_Huangzj(發糞塗牆)
-- Date    :2013-01-15 23:16:48
-- Version:
--      Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (Intel X86) 
--	Jun 17 2011 00:57:23 
--	Copyright (c) Microsoft Corporation
--	Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go 
create table [huang]([学号] int,[课程] varchar(1),[分数] int)
insert [huang]
select 1,'A',90 union all
select 2,'B',30 union all
select 1,'C',67
--------------开始查询--------------------------

declare @s nvarchar(4000)
set @s=''
Select     @s=@s+','+quotename('课程'+[课程])+'=sum(case when [课程]='+quotename([课程],'''')+' then [分数] else 0 end)'
from [huang] group by [学号],[课程]
exec('select [学号]'+@s+' from [huang] group by [学号]')
----------------结果----------------------------
/* 
学号          课程A         课程C         课程B
----------- ----------- ----------- -----------
1           90          67          0
2           0           0           30

(2 行受影响)

*/
美到心痛 2013-01-15
  • 打赏
  • 举报
回复
上面的逗号有问题 select id,sum(case when 课程='A' then 分数 else 0 end ) 课程A, sum(case when 课程='B' then 分数 else 0 end ) 课程B, sum(case when 课程='C' then 分数 else 0 end ) 课程C, sum(case when 课程='D' then 分数 else 0 end ) 课程D from table group by id
美到心痛 2013-01-15
  • 打赏
  • 举报
回复
select id,sum(case when 课程='A' then 分数 else 0 end ) 课程A, sum(case when 课程='B' then 分数 else 0 end ) 课程B, sum(case when 课程='C' then 分数 else 0 end ) 课程C, sum(case when 课程='D' then 分数 else 0 end ) 课程D from table group by id
szm341 2013-01-15
  • 打赏
  • 举报
回复
你想的很接近了 select id, sum(case when class='A' then fenshu else 0 end) A, sum(case when class='B' then fenshu else 0 end) B, sum(case when class='C' then fenshu else 0 end) C from table;
Jill_Yao 2013-01-15
  • 打赏
  • 举报
回复
能稍具体点吗,还是没明白
美到心痛 2013-01-15
  • 打赏
  • 举报
回复
用sum(case when )就可以了

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧