选择最高优先级行

时间:2011-09-20 05:40:15

标签: sql database oracle oracle10g

假设我有一个包含三列的表格keyvaluepriority,其中包含一个唯一键(keypriority)。< / p>

我想选择所有key / value对,其中该密钥的priority高于同一key的任何其他优先级。

例如:

key | value   | priority
----------------------
'a' | 'Alice' |   5 
'a' | 'Aaron' |   10
'b' | 'Bob'   |   1

应该返回:

key | value
-------------
'a' | 'Aaron'
'b' | 'Bob'

编写此类查询的有效方法是什么?

3 个答案:

答案 0 :(得分:5)

select [key],
       value
from (select [key],
             value,
             row_number() over(partition by [key] 
                               order by priority desc) as rn
      from YourTable) as T
where rn = 1

答案 1 :(得分:3)

    SELECT a.`key`,
           a.`value`
      FROM tbl a
INNER JOIN (SELECT MAX(priority) priority,
                   `key`
              FROM tbl
          GROUP BY `key`) b ON a.`key` = b.`key`
                           AND a.priority = b.priority

只要每个密钥只有一个且值最高的优先级

,此查询就会起作用

答案 2 :(得分:0)

使用此SQL:

SELECT key, value 
FROM T1 as t1
JOIN 
(SELECT key, MAX(priority) AS priority 
 FROM T1 as t2 
 GROUP BY key) as t3 
ON t1.key = t3.key AND t3.priority = t1.priority