一张成绩表, 学生编号,课程,成绩 课程有五门:数学,语文,英语,政治,历史。
学生 数学 语文 英语 政治 历史
张三 40 45 45 45 45
请教SQL如何写
select
s.stuname,c1.totalscore,c2.totalscore,c3.totalscore,
c4.totalscore,c5.totalscore
from
student s full join
((((
chengji c1 left join chengji c2
on c1.topless=0 and c2.topless=1 and c1.stuid=c2.stuid)
left join chengji c3
on c3.topless=2 and c1.stuid=c3.stuid)
left join chengji c4
on c4.topless=3 and c1.stuid=c4.stuid)
left join chengji c5
on c5.topless=4 and c1.stuid=c5.stuid)
on s.stuid=c1.stuid where s.stuid=102
这是我的sql 语句 但是总是有错误 。
当数学 没有分数时,仍能查询出值。 展开
如下:
select s.name,
sum(case topless when 0 then totalscore else 0 end)数学,
sum(case topless when 1 then totalscore else 0 end)语文,
sum(case topless when 2 then totalscore else 0 end)英语,
sum(case topless when 3 then totalscore else 0 end)政治,
sum(case topless when 4 then totalscore else 0 end)历史,
from student s left join chengji c on s.stuid=c.stuid
group by s.name,s.stuid
SQL功能
1、SQL数据定义功能:能够定义数据库的三级模式结构,即外模式、全局模式和内模式结构。在SQL中,外模式又叫做视图(View),全局模式简称模式(Schema),内模式由系统根据数据库模式自动实现,一般无需用户过问。
2、SQL数据操纵功能:包括对基本表和视图的数据插入、删除和修改,特别是具有很强的数据查询功能。
3、SQL的数据控制功能:主要是对用户的访问权限加以控制,以保证系统的安全性。
DECLARE @sql NVARCHAR(MAX)
SET @sql = 'SELECT [stuid]'
SELECT @sql = @sql + ',
SUM(CASE WHEN [topless] = ' + CAST([topless] AS NVARCHAR(255)) + ' THEN [score] END) AS topless' + CAST([topless] AS NVARCHAR(255))
FROM ( SELECT DISTINCT [topless] FROM chengji ) t
SET @sql = @sql + '
FROM chengji
GROUP BY [stuid]
'
PRINT @sql
EXEC sys.sp_executesql @sql
最后拼接的sql应该是类似这样
SELECT [stuid],
SUM(CASE WHEN [topless] = 1 THEN [score] END) AS topless1,
SUM(CASE WHEN [topless] = 2 THEN [score] END) AS topless2,
SUM(CASE WHEN [topless] = 3 THEN [score] END) AS topless3
FROM chengji
GROUP BY [stuid]
sum(case topless when 0 then totalscore else 0 end)数学,
sum(case topless when 1 then totalscore else 0 end)语文,
sum(case topless when 2 then totalscore else 0 end)英语,
sum(case topless when 3 then totalscore else 0 end)政治,
sum(case topless when 4 then totalscore else 0 end)历史
from student s left join chengji c on s.stuid=c.stuid
group by s.name,s.stuid
max(case when object='数学' then Score else 0 end) as '语文',
max(case when object='数学' then Score else 0 end) as '英语',
max(case when object='数学' then Score else 0 end) as '政治',
max(case when object='数学' then Score else 0 end) as '历史' from Student Group by name
这个sql语句就行了,不过可能列名和你的不一样,这个方式叫做行转列