如何在加入/子查询SQL时维护行的顺序

时间:2016-11-08 07:23:10

标签: sql-server

我有2张桌子

students:

      id   | name | age
      1      abc   20
      2      xyz   21

scores:

   id | studentid | marks
    1       1        20
    2       2        22
    3       2        20
    4       1        22
    5       1        20

其中studentid是学生表的外键

什么时候做

select studentid 
from scores 
where marks=20;

我得到以下结果     1, 2, 1

但是如果想要学生姓名的名称和我使用

进行联接的时候
 select t1.name 
 from students t1 
 inner join scores t2 on t1.id = t2.studentid 
 where t2.marks=20; 

我得到xyz,abc,abc虽然输出是正确的,但是有什么办法可以维持得分表中分数列出的顺序吗?我应该以{{1​​}}作为输出。我也试过使用子查询

abc,xyz,abc

但这也没有给我正确的订单。

1 个答案:

答案 0 :(得分:1)

    ;with cte as(
        select t2.id, t1.name 
         from students t1 
         inner join scores t2 on t1.id = t2.studentid 
         where t2.marks=20)
    select name from cte order by id

OUPUT
======
abc
xyz
abc