gpt4 book ai didi

sql-server - SQL : Using Top 1 in UNION query with Order By

转载 作者:行者123 更新时间:2023-12-02 03:27:25 25 4
gpt4 key购买 nike

我有一个表格如下

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

我应该找到当前日期及之后有效的所有费率。因此,为了获得当前的有效率,我使用

SELECT TOP 1 * from table 
where effective_date < '05/05/2009'
order by effective date desc

对于当前日期之后的费率,查询为

SELECT * from table 
where effective_date > '05/05/2009'

为了结合这两个结果,我使用联合作为

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

我不知道为什么会发生这种情况?有什么建议吗?

最佳答案

它的工作原理是这样的:

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-server - SQL : Using Top 1 in UNION query with Order By,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/842798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com