sql 一对多查询

2024-11-17 21:25:52
推荐回答(3个)
回答1:

交给我吧,典型的交叉查询,行列转换
select s.StudentName,
(case r.Subject when '语文' then r.Math end) as 语文,
(case r.Subject when '数学' then r.Math end) as 数学,
(case r.Subject when '英语' then r.Math end) as 英语,
(case r.Subject when '物理' then r.Math end) as 物理,
(case r.Subject when '地理' then r.Math end) as 地理
from Student s,Results r
where s.StudentId=r.StudentId

能用的话记得给分哦~

回答2:

http://hi.baidu.com/xckouy/blog/item/acb9196b010f60e142169409.html 方法二
http://hi.baidu.com/xckouy/blog/item/59f80adb342eaec38c10293f.html
处理多行转一行,使用动态会更简单点!
--参照下列处理成绩表(可以有问题),再联合学生表查询
SELECT
B.StudentId,
LEFT(UserList,LEN(UserList)-1) as paths
FROM
(
SELECT
StudentId,
(
SELECT
Subject +',' +Math
FROM
Results
WHERE
StudentId= A.StudentId
ORDER BY
StudentId FOR XML PATH('')
) AS UserList
FROM
Results A
GROUP BY
StudentId
)
B

回答3:

数据库表本身设计不合理
要求的表也不合理

另外你的成绩表前后是不是不一致?