我正在使用SQL Server 2014,我有以下运行正常的T-SQL查询:
SELECT Id, Name from TravelAgency
此查询输出的最后一行如下所示:
Id Name
--- ----
--- ----
715 AB Ltd
我想"手动"将以下值附加到此查询的结果集:(999,XY Ltd),以便运行修改后的查询将给出以下结果:
Id Name
--- ----
--- ----
715 AB Ltd
999 XY Ltd
为简化起见,查询会从TravelAgency表中提取请求的数据,并在输出的末尾添加指定的值。我需要在查询中添加这些特定值,但我无法弄清楚如何操作!
答案 0 :(得分:4)
使用union all:
select id, name from xxx -- is your query
union all
select 999 as id, 'XY Ltd' as name
编辑: 除了@ThorstenKettner的评论:如果ID不是数字或由于任何原因您无法使用它进行排序,那么您可以这样做:
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
答案 1 :(得分:3)
使用UNION
附加您需要的条目以及返回结果集。如果999 XY Ltd
条目已存在,则可以避免。
SELECT Id, Name FROM TravelAgency
UNION
SELECT 999 AS [Id], 'XY Ltd' AS [Name]
如果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