SQL:在 UNION 查询中使用 Top 1 和 Order By [英] SQL: Using Top 1 in UNION query with Order By
本文介绍了SQL:在 UNION 查询中使用 Top 1 和 Order By的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一张如下表
Rate Effective_Date
---- --------------
5.6 02/02/2009
5.8 05/01/2009
5.4 06/01/2009
5.8 12/01/2009
6.0 03/15/2009
我应该找到在当前日期和之后有效的所有费率.所以为了获得当前的有效率,我使用
I am supposed to find the all rates that are effective for current date and after it. So to get the current effective rate, i use
SELECT TOP 1 * from table
where effective_date < '05/05/2009'
order by effective date desc
对于查询是当前日期之后的费率
for the rates after the current date the query is
SELECT * from table
where effective_date > '05/05/2009'
为了结合这两个结果,我使用联合作为
To combine these two result i use a union as
SELECT TOP 1 * from table
where effective_date < '05/05/2009'
order by effective date desc
UNION
SELECT * from table
where effective_date > '05/05/2009'
预期的结果是
Rate Effective Date
---- --------------
5.8 05/01/2009
5.4 06/01/2009
5.8 12/01/2009
6.0 03/15/2009
但我得到的实际结果为
Rate Effective Date
---- --------------
5.6 02/02/2009
5.4 06/01/2009
5.8 12/01/2009
6.0 03/15/2009
我不知道为什么会发生这种情况?有什么建议吗?
I don't have a clue as to why this happens? Any suggestions?
推荐答案
它是这样工作的:
select *
from (
select top 1 *
from table
where effective_date <= '05/05/2009'
order by effective_date desc
) as current_rate
union all
select *
from table
where effective_date > '05/05/2009'
这篇关于SQL:在 UNION 查询中使用 Top 1 和 Order By的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文