我有一个表TAB有两个字段A和B,A是Varchar2(50)和B是Date.
假设我们有这些值:
A | B
------------------
a1 | 01-01-2013
a2 | 05-05-2013
a3 | 06-06-2013
a4 | 04-04-2013
Run Code Online (Sandbox Code Playgroud)
我们需要将字段的值A对应于字段的最大值B,这意味着我们需要返回a3.
我提出了这个要求:
select A
from TAB
where
B = (select max(B) from TAB)
Run Code Online (Sandbox Code Playgroud)
但我想避免在此解决方案中嵌套选择.
您对该解决方案有所了解吗?
谢谢
我做了一个sqlfiddle,其中列出了 4 种不同的方法来实现你想要的。请注意,我在您的示例中添加了另一行。所以你有两行具有最大日期。看到查询之间的区别了吗?Manoj 的方法只会给您一行,但有 2 行符合条件。您可以单击“查看执行计划”来查看 SQL Server 处理这些查询的方式的差异。
4 种不同的方式(用标准 SQL 编写,它们应该适用于每个 RDBMS):
select A
from TAB
where
B = (select max(B) from TAB);
select top 1 * from tab order by b desc;
select
*
from
tab t1
left join tab t2 on t1.b < t2.b
where t2.b is null;
select
*
from
tab t1
inner join (
select max(b) as b from tab
) t2 on t1.b = t2.b;
Run Code Online (Sandbox Code Playgroud)
借助 a_horse_with_no_name,还有另外两种特别针对 SQL Server 的方法:
select *
from (
select a,
b,
rank() over (order by b desc) as rnk
from tab
) t
where rnk = 1;
select *
from (
select a,
b,
max(b) over () as max_b
from tab
) t
where b = max_b;
Run Code Online (Sandbox Code Playgroud)
看到他们在这里工作。