简体   繁体   English

为评估为真的 IN 条件元素设置限制

[英]Set limit for IN condition element that evaluate true

table: t
+--------------+-----------+-----------+
| Id           | price     | Date      |
+--------------+-----------+-----------+
|  1           | 30        | 2021-05-09|
|  1           | 24        | 2021-04-26|
|  1           | 33        | 2021-04-13|
|  2           | 36        | 2021-04-18|
|  3           | 15        | 2021-04-04| 
|  3           | 33        | 2021-05-06|
|  4           | 46        | 2021-02-16|
+--------------+-----------+-----------+

I want to select rows where id is 1,2,4 and get maximum 2 row for each id by date descending order.我想 select 行,其中 id 为 1,2,4,并按日期降序获取每个 id 的最大 2 行。

+--------------+-----------+-----------+
| Id           | price     | Date      |
+--------------+-----------+-----------+
|  1           | 30        | 2021-05-09|
|  1           | 24        | 2021-04-26|
|  2           | 36        | 2021-04-18|
|  4           | 46        | 2021-02-16|
+--------------+-----------+-----------+

Something like:就像是:

Select * from t where Id IN ('1','2','4') limit 2 order by Date desc; 

this will limit the overall result fetched.这将限制获取的整体结果。

Use row_number() :使用row_number()

select id, price, date
from (select t.*,
             row_number() over (partition by id order by date desc) as seqnum
      from t
      where id in (1, 2, 4)
     ) t
where seqnum <= 2;

Probably the most efficient method is a correlated subquery:可能最有效的方法是相关子查询:

select t.*
from t
where t.id in (1, 2, 4) and
      t.date >= coalesce( (select t2.date
                           from t t2
                           where t2.id = t.id
                           order by t2.date desc
                           limit 1,1
                           ), t.date
                        );

For performance, you want an index on (id, date) .为了提高性能,您需要(id, date)上的索引。 Also, this can return duplicates if there are multiple rows for a given id on the same date.此外,如果在同一日期给定 id 有多行,这可能会返回重复项。

Here is a db<>fiddle. 是一个 db<>fiddle。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM