1

我有一个键值对表,第三列代表一些权重。我想要的只是根据权重值递减为每对拾取前 n 行。

是否有任何主流 sql 技术支持任何自然的方式来做到这一点?还是我必须总是包括一些黑客...

示例数据:

key value   weight   
15391   22877   8    
15391   24311   7    
15391   460     7    
22634   22877   6   

我想为每对选择前 2 行,即结果应该是:

15391   22877   8    
15391   24311   7        
22634   22877   6 
4

2 回答 2

4

我认为您的描述具有误导性,您真正想要的是:

select key, value, weight
from (
    select *,
        row_number() over(partition by key order by weight desc) rn
    from aggregated_table
) s
where rn <= 2
order by weight desc, key

以上将适用于 Postgresql 和 SQL Server。这将在 MySQL 中有效,但在 SQL Server 中无效:

select key, value, (
    select weight
    from aggregated_table
    where key = s.key
    order by weight desc
    limit 1
    ) weight
from aggregated_table
union
select key, value, (
    select weight
    from aggregated_table
    where key = s.key
    order by weight desc
    limit 1 offset 2
    ) weight
from aggregated_table
order by weight desc, key
于 2013-03-25T14:07:55.110 回答
3

这在 Postgres 中很容易做到:

select key, value, weight
from (select key, value, weight, row_number() over (partition by key, value order by weight desc) as seqnum
      from t
     ) t
where seqnum <= 2

如果您想要一个同时适用于 MySQL 和 Postgres 的版本,请使用相关子查询:

select key, value, weight
from (select key, value, weight,
             (select count(*) from t t2 where t2.key = t.key and t2.value = t.value and t2.weight >= t.weight
             ) as seqnum
      from t
     ) t
where seqnum <= 2
于 2013-03-25T13:56:04.783 回答