首页 新闻 会员 周边

求SQL语句

0
[待解决问题]

求sql查询语句,大神们请多指教。。。。。。。。。。。

恋人星空的主页 恋人星空 | 菜鸟二级 | 园豆:260
提问于:2014-10-31 14:35
< >
分享
所有回答(11)
0

select * from table where score=100 and scale =40 and subject ="数学"

男人要爽 | 园豆:6 (初学一级) | 2014-10-31 14:52
0

select name

,max(case subject when '数学' then score else 0 end) as 数学

,max(case subject when '数学' then scale else 0 end) as 数学scale

,max(case subject when '语文' then score else 0 end) as 语文

,max(case subject when '语文' then scale else 0 end) as 语文scale

,max(case subject when '英语' then score else 0 end) as 数学

,max(case subject when '英语' then scale else 0 end) as 英语scale

,sum(score*scale/100) as 总分

from table

group by name

米修君 | 园豆:553 (小虾三级) | 2014-10-31 16:00
1

pivot

风醉 | 园豆:1197 (小虾三级) | 2014-10-31 16:06
0

select a.*,cast((数学*数学scale+语文*数学scale+英语*英语scale) as float)/100 as 总分

from (

select name,

max(case subject when '数学' then score else 0 end) as 数学,

max(case subject when '数学' then scale else 0 end) as 数学scale,

max(case subject when '语文' then score else 0 end) as 语文,

max(case subject when '语文' then scale else 0 end) as 语文scale,

max(case subject when '英语' then score else 0 end) as 英语,

max(case subject when '英语' then scale else 0 end) as 英语scale

from tablename

group by name

) as a 

会飞的金鱼 | 园豆:881 (小虾三级) | 2014-10-31 16:08

麻烦问下,为啥要用max

支持(0) 反对(0) 恋人星空 | 园豆:260 (菜鸟二级) | 2014-10-31 16:42

@恋人星空: 

拿第一个case when来说:当subject='数学'时,值为score字段中的数据,否则为0

列名:        Name           数学

数据:        张三             100

                张三              0

                张三              0

这个时候就需要group by name统计数据,select筛选的字段除group by后面字段之外,必须是聚合函数计算得到的结果,max()得到的值才是张三数学科目实际对应的分数,其实用sum()函数也可以。

其他科目类似。

其实主要要考虑的是行转列。

支持(0) 反对(0) 会飞的金鱼 | 园豆:881 (小虾三级) | 2014-10-31 17:05

@会飞的金鱼: 讲的很好,十分感谢,我明白了

支持(0) 反对(0) 恋人星空 | 园豆:260 (菜鸟二级) | 2014-10-31 18:09
0

可以

潇洒一世 | 园豆:202 (菜鸟二级) | 2014-10-31 16:16
0

are you meizi?

+小马哥++ | 园豆:906 (小虾三级) | 2014-11-01 12:12
0
邀月 | 园豆:25475 (高人七级) | 2014-11-03 07:49
0

行转列

我是糖糖 | 园豆:446 (菜鸟二级) | 2014-11-03 09:15
0
select "Name",
sum(case "Subject" when '数学' then "Score" else 0 end) 数学,
sum(case "Subject" when '数学' then "Scale" else 0 end) "数学 scale",
sum(case "Subject" when '语文' then "Score" else 0 end) 语文,
sum(case "Subject" when '语文' then "Scale" else 0 end) "语文 scale",
sum(case "Subject" when '英语' then "Score" else 0 end) 英语,
sum(case "Subject" when '英语' then "Scale" else 0 end) "英语 scale",
sum("Score"*"Scale"/100) 总分
from "成绩" group by "Name"

有图,有真相,楼主好好看吧。

王倩2110 | 园豆:200 (初学一级) | 2014-11-05 16:41

非常感谢你的回答,学习了

支持(0) 反对(0) 恋人星空 | 园豆:260 (菜鸟二级) | 2014-11-05 18:25
0
1 SELECT * FROM [TABLE] PIVOT ( MAX(SCORE), MAX(SCALE) SCALE FOR SUBJECT IN ('数学', '语文', '英语') )
过于执著 | 园豆:339 (菜鸟二级) | 2015-01-07 17:13
1 SELECT * FROM [TABLE] PIVOT ( SUM(SCORE), SUM(SCALE) SCALE FOR SUBJECT IN ('数学', '语文', '英语') )

总分自己计算一下,

支持(0) 反对(0) 过于执著 | 园豆:339 (菜鸟二级) | 2015-01-07 17:15
0
定位I搜索 | 园豆:194 (初学一级) | 2015-01-27 20:54
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册