【发布时间】:2011-07-22 13:22:00
【问题描述】:
鉴于:
需要过滤的两个查询:
select top 2 t1.ID, t1.ReceivedDate
from Table t1
where t1.Type = 'TYPE_1'
order by t1.ReceivedDate desc
还有:
select top 2 t2.ID
from Table t2
where t2.Type = 'TYPE_2'
order by t2.ReceivedDate desc
另外,这些返回我正在寻找的 IDs:(13, 11 和 12, 6)
基本上,我想要两种特定类型数据的两条最新记录。
我想像这样将这两个查询合并在一起:
select top 2 t1.ID, t2.ReceivedDate
from Table t1
where t1.Type = 'TYPE_1'
order by ReceivedDate desc
union
select top 2 t2.ID
from Table t2
where t2.Type = 'TYPE_2'
order by ReceivedDate desc
问题:
问题是这个查询无效,因为如果第一个select 是unioned,它就不能有order by 子句。如果没有order by,它就不可能有top 2。
我该如何解决这种情况?
【问题讨论】:
-
我猜你的意思是
order by不是where有问题。
标签: sql-server union where-clause