SQL在满足条件后选择每个组中的所有行

问题描述 投票:0回答:2

我想在最后一次满足该组的条件之后为每个组选择所有行。该related question具有使用相关子查询的答案。

就我而言,我将拥有数以百万计的类别和数以亿计的行。 是否有一种方法可以使用性能更高的查询获得相同的结果?

这里是一个例子。条件是条件列中最后一个0之后的所有行(每组)。

category | timestamp |  condition 
--------------------------------------
   A     |     1     |     0 
   A     |     2     |     1 
   A     |     3     |     0 
   A     |     4     |     1
   A     |     5     |     1
   B     |     1     |     0 
   B     |     2     |     1
   B     |     3     |     1

我想达到的结果是

category | timestamp |  condition 
--------------------------------------
   A     |     4     |     1
   A     |     5     |     1
   B     |     2     |     1
   B     |     3     |     1
sql correlated-subquery
2个回答
0
投票

如果要在最后一个0之后保留所有内容,则可以使用窗口功能:

select t.*
from (select t.*,
             max(case when condition = 0 then timestamp end) over (partition by category) as max_timestamp_0
      from t
     ) t
where timestamp > max_timestamp_0 or
      max_timestamp_0 is null;

(category, condition, timestamp)上有索引,相关的子查询版本也可能执行得很好:

select t.*
from t
where t.timestamp > all (select t2.timestamp
                         from t t2
                         where t2.category = t.category and
                               t2.condition = 0
                        );

0
投票

您可能想尝试窗口功能:

select category, timestamp, condition
from (
    select 
        t.*,
        min(condition) over(partition by category order by timestamp desc) min_cond
    from mytable t
) t
where min_cond = 1

带有min()子句的窗口order by计算同一condition的当前行和后续行的category的最小值:我们可以将其用作过滤器,以消除后跟[ C0]

© www.soinside.com 2019 - 2024. All rights reserved.