简体   繁体   English

如何将具有特定值的行附加到我的T-SQL查询的输出中?

[英]How do I append a row with specific values to the output of my T-SQL query?

I am using SQL Server 2014 and I have the following T-SQL query which runs fine: 我正在使用SQL Server 2014,我有以下运行良好的T-SQL查询:

SELECT Id, Name from TravelAgency

The last row of the output of this query is shown below: 此查询的输出的最后一行如下所示:

Id       Name
---      ----
---      ----
715      AB Ltd

I want to "manually" append the following values to the result set of this query: (999, XY Ltd) so that running the modifed query will give me the following results: 我想“手动”将以下值附加到此查询的结果集:(999,XY Ltd),以便运行修改后的查询将给出以下结果:

Id       Name
---      ----
---      ----
715      AB Ltd
999      XY Ltd

To simplify, the query pulls the data requested from the TravelAgency table and ADDS the specified values at the end of the output. 为简化起见,查询从TravelAgency表中提取请求的数据,并在输出结束时ADDS指定的值。 I need to add those specific values in my query but I just can't figure out how to do it! 我需要在查询中添加这些特定值,但我无法弄清楚如何做到这一点!

Use a union all: 使用联合全部:

select id, name from xxx -- is your query
union all
select 999 as id, 'XY Ltd' as name 

EDIT: In addition to @ThorstenKettner 's comment: If ID is not nummeric or for any reason you can not use it for the sort, then you could do it like this: 编辑:除了@ThorstenKettner的评论:如果ID不是nummeric或由于任何原因你不能使用它进行排序,那么你可以这样做:

select ID, Name
from 
(
    select 1 as SpecialSort, ID, Name from xxx -- is your query
    union all
    select 2 as SpecialSort, 999 as ID, 'XY Ltd' as Name
) AllData
order by SpecialSort asc -- like this your manually added row will appear at the end

Use UNION to append your required entry along with return result set. 使用UNION附加所需的条目以及返回结果集。 It can avoid if the 999 XY Ltd entry is already exists. 如果999 XY Ltd条目已经存在,则可以避免。

SELECT Id, Name FROM TravelAgency
UNION 
SELECT 999 AS [Id], 'XY Ltd' AS [Name]

If the 999 XY Ltd is already return form result set and allow the duplicate entries you can use UNION ALL and ensure the 999 XY Ltd as last record by ORDER BY 如果999 XY Ltd已经返回表格结果集并允许重复输入,您可以使用UNION ALL并确保将999 XY Ltd作为ORDER BY最后一条记录

SELECT Id, Name FROM (
    SELECT Id, Name FROM TravelAgency
    UNION ALL
    SELECT 999 AS [Id], 'XY Ltd' AS [Name]
) AS T 
ORDER BY Id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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