sql - 选择 max dense_rank() = value 的所有位置?
问题描述
我有使用dense_rank的代码,按ID分区并按val2排序。我想选择任何给定 ID 的最大排名为 2 的所有行。
下面的代码为初始步骤提供了正确的输出。
Select distinct
`account id`, `val2`, distinct_rank, observation_total
from ( Select
`account id`, `val2`, dense_rank()
over (partition by `account id` order by `val2` desc) as distinct_rank,
count(*)
over (partition by `account id` order by `val2` desc) as observation_total
from TABLE1 );
样本结果:
account id | val2 | distinct_rank
___________________________________
1 | a | 1
2 | a | 1
2 | b | 2
2 | c | 3
3 | d | 1
3 | e | 2
所以我需要一个查询,它只选择每个帐户 id 的最大 distinct_rank = 2 或其他值的行。
例如,如果 max distinct_rank per account id = 2,结果将是:
account id | val2 | distinct_rank
___________________________________
3 | d | 1
3 | e | 2
This is because account id = 3 has a max distinct_rank of 2.
我知道如何选择 max rank = 2,我可以只做一个查询,上面写着“select * where account id in a subquery that grab all with max distinct_rank = 2”,但我觉得可能会有更好/更有效方法?
解决方案
select
*
from table1 a
cross apply(
select count(distinct val2) dist_qnt
from table1 b where b.[account id] = a.[account id]
) ca
where ca.dist_qnt = 2;
或者使用这篇文章中的方法。
select *
from (
select
*,
dense_rank() over(
partition by [account id] order by val2
) +
dense_rank() over(
partition by [account id] order by val2 desc
) - 1 as dist_qnt
from table1
) sq
where dist_qnt = 2;
但要考虑 NULL 值。
SQL Fiddle上的演示。
推荐阅读
- matlab - 如何从低通滤波器功能(firrrcos 或 rcosdesign)创建高通滤波器?MATLAB
- java - 通过 logger.log 覆盖处理程序级别
- encoding - 阿拉伯标签在 Geoserver 中无法正确显示
- javascript - 在 JavaScript 中等待 promise 时究竟会发生什么?
- git - 如何在不使用强制推送的情况下解决 rebase 冲突后将分支推送到远程?
- javascript - 如何在提示中添加内容并在节点程序中获取输出?
- java - 如何使用支持中断(暂停、连接丢失……)的 Spring Boot 开发获取端点?
- c - 当按位与应用于负数时会发生什么?
- asterisk - 如何限制话单文件中的通话记录数
- codenameone - 请求线程中断在 Ios 上不起作用