[英]SQL Server : select all rows from a column after the 1st row with matching value from the same column
Table1 -
ID | Name
--------
1 | Jos
2 | Tim
3 | Karl
4 | Joe
5 | Tom
Output I am looking for我正在寻找的输出
Name
Tom
Jos
Tim
Karl
Joe
so the output should consist the matching and non-matching values, but the matching value in the first row.所以输出应该包括匹配和不匹配的值,但第一行中的匹配值。
I have tried something like below but I am not able to get the matching value in the first row.我已经尝试过类似下面的方法,但我无法在第一行中获得匹配的值。
select distinct Name
from(
SELECT Name
FROM table1
WHERE Id = 5
UNION SELECT Name
FROM table1) temp
select name
from your_table
order by case when id = 5
then 1
else 2
end,
id
The @Juergen answer +1 is what I would probably use, but your union approach might even perform well, so here is how you can make it work: @Juergen 答案 +1 是我可能会使用的,但您的联合方法甚至可能表现良好,因此您可以通过以下方式使其发挥作用:
SELECT name
FROM
(
SELECT name, 1 AS ord FROM table1 WHERE id = 5
UNION ALL
SELECT name, 2 FROM table1 WHERE id <> 5
) t
ORDER BY ord;
The trick here is to introduce a computed column ord
which keeps track of whether a name matches and should appear first.这里的技巧是引入一个计算列ord
来跟踪名称是否匹配并应该首先出现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.