首页 > 解决方案 > 如何根据最大列值找到对应的行数据?

问题描述

我想取每个分区块的最大值并找到相关的 id(在同一行中)。然后,我想使用单数 show_id 作为“获胜者”,并使用匹配的 show_id 对同一分区中的所有行进行 bool_flag。

我在实现这一点时遇到了麻烦,尤其是窗口函数——我遇到了多个问题,说不支持子查询,或者“必须出现在 GROUP BY 子句中或在聚合函数 sql 中使用”

subQ1 as (
select subQ0.*,
   case

   **when show_id = 
   (select id from (select show_id, max(rn_max_0)
   over (partition by tv_id, show_id)))** 

   then 1
   else 0
   end as winner_flag

from subQ0

)

我有的:

tv_id     show_id       partition_count
1           42              1
1           42              2
1           42              3
1           7               1
2           12              1
2           12              2
2           12              3
2           27              1

我想要的是:

tv_id     show_id       partition_count      flag    
1           42              1                  1
1           42              2                  1
1           42              3                  1
1           7               1                  0
2           12              1                  1
2           12              2                  1
2           12              3                  1
2           27              1                  0

因为 tv_id 1 与 show_id 42 的连接最多,所以这些行会被标记。

理想情况下,类似于SQL 的东西只选择列上具有最大值的行,但是分区和分组导致了问题。这个数据集也有数十亿行,所以联合将是一场噩梦。

提前致谢!

标签: sql

解决方案


对于每个tv_id,您似乎都希望show_id出现最多的那个。如果是这样:

select s.*,
       (case when cnt = max(cnt) over (partition by tv_id)
             then 1 else 0
        end) as flag
from (select s.*, count(*) over (partition by tv_id, show_id) as cnt
      from subQ0 s
     ) s;

推荐阅读