简体   繁体   中英

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM