简体   繁体   English

SQL Server:从同一列中具有匹配值的第一行之后的列中选择所有行

[英]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.

相关问题 SQL Server:联接两行。 第一列的所有列和第二列的第一列使用别名 - SQL Server : Join two rows. All columns from the 1st and 1 column from the second using an alias SQL为A列第1行选择值,然后从B列第1行选择值,然后从A列第2行…全部在单独的行上 - SQL Select vale for Column A Row 1, then Value from Column B Row 1, then Column A Row 2…all on separate rows T-SQL从第一个选择的值在第二个选择联合的每一行 - T-SQL Value from 1st select on each row in 2nd select of a union all 如何从SQL Server中的列中删除第一个字符 - How to remove the 1st character from a column in SQL Server 列第 2 行的值复制到下一列的第 1 行 - Value from 2nd Row of column copied to 1st row of next column 基于 SQL 服务器中 select 查询中第一列值的值格式 - Value format based on 1st Column value in select query in SQL server SQL选择链接表中所有行在x列中具有相同值的行 - SQL Select rows where all rows from linked table have the same value in column x SQL Server 2008基于列值选择表的所有列+来自同一表的列 - SQL Server 2008 Select all columns of a table + a column from the same table based on a column value SQL Server:排除表中的行如果有另一行具有相同的col值和特定的二级列值 - SQL Server : excluding rows from a table IF there is another row with the same col value and a particular secondary column value SQL SERVER:(性能问题)获取所有行,如果该列重复,则从 select 语句中选择另一列的最大行 - SQL SERVER:(performance issue) get all rows and if the column is duplicated select the max row of another column from the select statement
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM