如何在SQL查询上使用最大日期

时间:2018-11-06 09:02:55

标签: sql sql-server oracle

我有sql查询问题;

Col1, Col2, Col3, Col4
aaaa, 2018.11.06, 8.0, 400.0
aaaa, 2018.06.06, 12.0, 600.0
aaaa, 2018.02.10, 10.0, 500.0
bbbb, 2017.11.06, 8.0, 100.0
bbbb, 2017.06.06, 12.0, 300.0
bbbb, 2017.02.10, 10.0, 200.0

在select语句中,我只需要获取最大(最新)的Col2。正确的结果必须是:

aaaa, 2018.11.06, 8.0, 400.0
bbbb, 2017.11.06, 8.0, 100.0

因为2018.11.06和2017.11.06是最大(最新)。

如何在MS SQL或ORACLE上的SQL查询中使用最大日期?

3 个答案:

答案 0 :(得分:3)

您可以使用相关子查询

select * from tablename a where col2 in 
   (select max(col2) from tablename b on a.col1=b.col1)

答案 1 :(得分:2)

相当普遍的解决方案可以

select yt.*
from your_table yt
join (
   select col1, max(col2) max_col2
   from your_table
   group by col1
) t on t.col1 = yt.col1 and
       t.max_col2 = yt.col2

此解决方案将返回所有带有col1的最大日期的行。另一个解决方案是使用row_numer(),但是它可以具有suboptimal performance

select *
from
(
  select *,
         row_number() over (partition by col1 order by col2 desc) rn
  from your_table
) t
where t.rn = 1

答案 2 :(得分:1)

SQL Server:

SELECT TOP 1 * FROM myTable ORDER BY Col2 DESC