不使用子查询查找最大 sID
Find max sID without subquery
我有一个“sSamples”table,其中包含 UniqueID、sDate 和 sID-s,例如:
我需要按最新 sDate 并按 UniqueID 分组的 SID-s。
结果应如下所示:
UniqueID | SID
---------------------
031311579 | 11641325
053600109 | 11641353
066051428 | 11641379
093468114 | 11641350
我尝试了不同的查询版本,但性能很慢。最好的解决方案是什么?
感谢您的回答!
您没有post您的版本是什么(这样我们就不会重新post您已经尝试过的版本)。无论如何,如果您没有尝试分析函数,方法如下(第 1 - 5 行的示例数据;您可能想尝试的查询从第 6 行开始):
SQL> with ssamples (uniqueid, sdate, sid) as
2 (select '031311579', to_date('18.01.2021 08:18', 'dd.mm.yyyy hh24:mi'), 11641325 from dual union all
3 select '066051428', to_date('20.01.2021 07:50', 'dd.mm.yyyy hh24:mi'), 11641381 from dual union all
4 select '066051428', to_date('20.01.2021 07:51', 'dd.mm.yyyy hh24:mi'), 11641379 from dual
5 )
6 select uniqueid, sid
7 from (select uniqueid, sdate, sid, row_number() over (partition by uniqueid order by sdate desc) rn
8 from ssamples
9 )
10 where rn = 1;
UNIQUEID SID
--------- ----------
031311579 11641325
066051428 11641379
SQL>
查看预期输出,您似乎可以将 max
与 keep
子句一起使用,如下所示
Select uniqueid, max(sid) keep (dense_rank last order by sdate) as sid
From your_table
Group by uniqueid
我有一个“sSamples”table,其中包含 UniqueID、sDate 和 sID-s,例如:
我需要按最新 sDate 并按 UniqueID 分组的 SID-s。
结果应如下所示:
UniqueID | SID
---------------------
031311579 | 11641325
053600109 | 11641353
066051428 | 11641379
093468114 | 11641350
我尝试了不同的查询版本,但性能很慢。最好的解决方案是什么?
感谢您的回答!
您没有post您的版本是什么(这样我们就不会重新post您已经尝试过的版本)。无论如何,如果您没有尝试分析函数,方法如下(第 1 - 5 行的示例数据;您可能想尝试的查询从第 6 行开始):
SQL> with ssamples (uniqueid, sdate, sid) as
2 (select '031311579', to_date('18.01.2021 08:18', 'dd.mm.yyyy hh24:mi'), 11641325 from dual union all
3 select '066051428', to_date('20.01.2021 07:50', 'dd.mm.yyyy hh24:mi'), 11641381 from dual union all
4 select '066051428', to_date('20.01.2021 07:51', 'dd.mm.yyyy hh24:mi'), 11641379 from dual
5 )
6 select uniqueid, sid
7 from (select uniqueid, sdate, sid, row_number() over (partition by uniqueid order by sdate desc) rn
8 from ssamples
9 )
10 where rn = 1;
UNIQUEID SID
--------- ----------
031311579 11641325
066051428 11641379
SQL>
查看预期输出,您似乎可以将 max
与 keep
子句一起使用,如下所示
Select uniqueid, max(sid) keep (dense_rank last order by sdate) as sid
From your_table
Group by uniqueid