Sql 一个查询中的多个查询,其中
我编写此查询是为了从两个表(所选项目:Sql 一个查询中的多个查询,其中,sql,sql-server,tsql,Sql,Sql Server,Tsql,我编写此查询是为了从两个表(所选项目:StudentId和score)中查找最高分数,现在我想从其他表中选择一些其他数据:(StudentName,StudentImage,…),这些表必须使用StudentId筛选项目 我的查询返回: StudentId HighScoreUser -1 250 -2 100 -3 90 -4 80 -5 40
StudentId
和score
)中查找最高分数,现在我想从其他表中选择一些其他数据:(StudentName
,StudentImage
,…),这些表必须使用StudentId
筛选项目
我的查询返回:
StudentId HighScoreUser
-1 250
-2 100
-3 90
-4 80
-5 40
为了在网格中显示数据,我需要学生姓名。。。因此,我必须使用StudentId
查找特定用户的信息:
CREATE PROCEDURE SelectTopYear
AS
SELECT TOP 5 StudentId, ISNULL(SUM(Score),0) As HighScoreUser
FROM (SELECT StudentId, Score FROM tbl_ActPoint
UNION ALL
SELECT StudentId, Score FROM tbl_EvaPoint
) as T
GROUP BY StudentId ORDER BY HighScoreUser DESC
RETURN 0
您可以使用CTE(或子查询)和JOIN
:
WITH s as (
SELECT TOP 5 StudentId, ISNULL(SUM(Score),0) As HighScoreUser
FROM (SELECT StudentId, Score FROM tbl_ActPoint
UNION ALL
SELECT StudentId, Score FROM tbl_EvaPoint
) s
GROUP BY StudentId
ORDER BY HighScoreUser DESC
)
SELECT . . .
FROM s JOIN
othertable ot
ON s.StudentId = ot.StudentId;
填写适当的列名和表名。什么其他表?内部连接到包含学生姓名的表…
现在我想选择一些其他数据:(StudentName,StudentImage,…
=>如果这些值对于单个学生id相同,那么在group by
中也使用这些值。否则,请确定每个学生id需要哪个列值,并执行这些列的聚合函数。在这种情况下,请给出一些包含所有所需列和预期输出的示例数据