繁体   English   中英

子查询中符合条件的每个组的最大值

[英]max of each group in subquery that matches a condition

我有一张桌子,如下所示。

我有一个包含10列的表格,我对其中4列感兴趣。 说出具有ID,名称,URL,排名的tableA。

id    |name    |url    |ranking
--------------------------------
1     |apple   |a1.com  |1
2     |apple   |a1.com  |2
3     |apple   |a1z.com |3
4     |orange  |o1.com  |1
5     |orange  |o1.com  |2
6     |apple   |a1.com  |4
7     |apple   |a1z.com |5
8     |orange  |o1z.com |6

我想要ID为7,6,3,2 8,5,4的行。 即对于每个组(苹果和橙子)-排名> max(rank)-3并且url中带有z的所有行。

对于苹果,id为7,其中带有z的url的最高排名为5

所以我想要排名> 5-3的苹果行。 排名大于2。

这是ID为7、6、3的行。

橙色组也是如此。 (编号为8,5,4的行)

您似乎希望每个组最多包含四个记录,并按排名排序:

select t.*
from (select t.*,
             row_number() over (partition by name order by ranking desc) as seqnum
      from t
     ) t
where seqnum <= 4
order by name, ranking desc;

糟糕,我刚刚记得。 Amazon Redshift不支持row_number() (或已解决此问题?)。 累积计数有效:

select t.*
from (select t.*,
             count(*) over (partition by name order by ranking desc range between unbounded preceding and current row) as seqnum
      from t
     ) t
where seqnum <= 4
order by name, ranking desc;

暂无
暂无

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

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