sql - 如何根据最大列值找到对应的行数据?
问题描述
我想取每个分区块的最大值并找到相关的 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 的东西只选择列上具有最大值的行,但是分区和分组导致了问题。这个数据集也有数十亿行,所以联合将是一场噩梦。
提前致谢!
解决方案
对于每个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;
推荐阅读
- angular - ngFor 在 Html 文件中不起作用,不显示来自服务器的数据
- python - 检查上周和最后到上周的熊猫
- javascript - 在 IE 11 中使用 java 脚本打开多个选项卡,但 UrlReferrer 不等于 null
- php - PDO bindValue 没有插入日期
- r - 有缺失值时按组躲避 geom_errorbar
- c - 使用 AVX512 将压缩 64 位整数转换为带符号饱和的压缩 8 位整数
- javascript - 选中复选框时,将文本框值乘以 0.9
- python - 为日期和时间分配数值
- http - 类型“HTTP”上不存在属性“setServerTrustMode”。(插件-高级-HTTP)
- hyperledger-fabric - 签名集不满足策略