Select 来自 table - SQL 的 2 个最近日期

Select 2 most recent dates from the table - SQL

我有一个 table 如下所示

ID_NUMBER SALEDATA 销售额
1 2020-09-07 47,000
2 2020-03-25 51,470
3 2021-06-12 32,000
4 2018-10-12 37,560

我想 select 仅包含 2 个最近日期的行。所以我想要的输出如下

ID_NUMBER SALEDATA 销售额
1 2020-09-07 47,000
3 2021-06-12 32,000

有人可以指导我在 SQL 中从哪里开始吗?我试过使用 MAX() 但它只给我最新的。

谢谢!

在标准 SQL 中,您将使用:

select t.*
from t
order by saledata desc
offset 0 row fetch first 2 row only;

并非所有数据库都支持 fetch first。它可能拼写为 limitselect top 或其他内容,具体取决于您的数据库。

另一种选择,具有rank解析功能。样本数据到第 7 行,查询从第 9 行开始。查看代码中的注释。

SQL> with test (id_number, saledata, saleamount) as
  2    -- sample data
  3    (select 1, date '2020-09-07', 47000 from dual union all
  4     select 2, date '2020-03-25', 51470 from dual union all
  5     select 3, date '2021-06-12', 32000 from dual union all
  6     select 4, date '2018-10-12', 37560 from dual
  7    )
  8  -- sort them by date in descending order, fetch the first two rows
  9  select id_number, saledata, saleamount
 10  from (select t.*,
 11          rank() over (order by saledata desc) rn
 12        from test t
 13       )
 14  where rn <= 2
 15  order by saledata;

 ID_NUMBER SALEDATA   SALEAMOUNT
---------- ---------- ----------
         1 2020-09-07      47000
         3 2021-06-12      32000

SQL>

select 数据集中的前 2 名按 saledata 列降序排列