联盟只选择一行

时间:2012-08-07 12:12:31

标签: sql

我有一个查询,两个选择条款与UNION结合。我想只选择前排第一行。我怎么能用联盟?

Select Fault,OccurredOn From ATMStatus Where Ticket=189703 // This Will retrieve single record as the primary key is applied
Union 
Select Fault,OccurredOn From ATMStatusHistory Where Resolved=0 AND Ticket=189703 Order By OccurredOn Desc

2 个答案:

答案 0 :(得分:2)

select top 1 * from 
(
                 Select Fault,OccurredOn 
                 From ATMStatus
                 Where Ticket=189703
                 Union 
                 Select Fault,OccurredOn
                 From ATMStatusHistory
                 Where Resolved=0 AND Ticket=189703
) x
Order By OccurredOn Desc

答案 1 :(得分:0)

这会返回2行:

select 1 as id
union
select 2 as id

返回1行:

select top 1 * from (
  select 1 as id
  union
  select 2 as id
) as x
order by id