我有一个问题。 这是故事,我有学生标记表(表 A )
Name Course Marks
Student 01 32472 44
Student 02 32472 80
Student 03 32472 67
Student 04 32472 76
Student 05 32472 56
Student 06 32472 98
Student 07 32472 13
Student 08 32472 68
Student 09 32472 84
Student 10 32472 93
我有奖章的表格(表 B )。
Medel Course CutOff
Silver 32472 0-69
Gold 32472 70 -84
Platinum 32472 85 -100
请您帮我在SQL中获取以下表格(表格)。
Name Course Medal
Student 01 32472 Silver
Student 02 32472 Gold
Student 03 32472 Silver
Student 04 32472 Gold
Student 05 32472 Silver
Student 06 32472 Platinum
Student 07 32472 Silver
Student 08 32472 Silver
Student 09 32472 Gold
Student 10 32472 Platinum
我如何加入表A(学生标记表)和表B(奖章截止标记表)然后获得决赛桌?
非常感谢您的回答/评论。
谢谢 加扬
答案 0 :(得分:2)
编辑后:
;WITH CteMedals AS(
SELECT *,
rStart = LEFT(CutOff, CHARINDEX('-', CutOff) - 1),
rEnd = SUBSTRING(CutOff, CHARINDEX('-', CutOff) + 1, LEN(CutOff) - CHARINDEX('-', CutOff))
FROM TableB
)
SELECT
a.Name, a.Course, ISNULL(b.Medal, 'Silver') AS Medal
FROM TableA a
OUTER APPLY(
SELECT TOP 1 Medal
FROM CteMedals
WHERE
a.Marks BETWEEN rStart AND rEnd
ORDER BY rEnd DESC
)b
您可以使用OUTER APPLY
:
SELECT
a.Name, a.Course, ISNULL(b.Medal, 'Silver') AS Medal
FROM TableA a
OUTER APPLY(
SELECT TOP 1 Medal
FROM TableB
WHERE
a.Marks >= CutOff
ORDER BY CutOff DESC
)b