我有两张桌子:
表#1 - 学生:
+------+-------+
|Roll | Name |
+------+-------+
| 1 | A |
| 2 | B |
| 3 | C |
+------+-------+
表#2 - 标记:
+------+------+
| Roll | Mark |
+------+------+
| 1 | 85 |
| 3 | 95 |
+------+------+
输出需要:
+-------+------+-------+---------+
| Roll | Name | Mark |Position |
+-------+------+-------+---------+
| 1 | A | 85 | 2 |
| 2 | B | 0 | 3 |
| 3 | C | 95 | 1 |
+-------+------+-------+---------+
获取输出的查询应该是什么?我认为rank
函数将被使用,但不知道使用它...
答案 0 :(得分:1)
使用LEFT JOIN
加入两个表,然后使用RANK()
。
<强>查询强>
select *, Position = rank() over(
order by t.Mark desc
)
from(
select t1.Roll, t1.Name, coalesce(t2.Mark, 0) as Mark
from student t1
left join Mark t2
on t1.Roll = t2.Roll
)t
order by t.Name;
答案 1 :(得分:0)
使用Left Join和Rank()函数。
查询
select T1.Roll, T1.Name, isnull(T2.Mark,0) Mark, rank() over(order by mark desc) Position
from STUDENT T1 left join MARK T2
on T1.Roll = T2.Roll order by T1.Roll