2011-09-20 106 views
2

可以說我有一個三列的表,key,valuepriority與一個唯一的鍵(key,priority)。選擇最高優先排

我想選擇所有key/value對,其中priority爲關鍵的是比任何其他優先級相同key更高。

例如:

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

應返回:

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

什麼是寫這樣的查詢的一種有效的方法?

+0

我希望看到的答案這個... –

+0

@mu太短:Oracle 10g – Clinton

+1

你想如何處理同樣優先級的關係 –

回答

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 
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 

這個查詢工作,只要每個鍵有且只有一個最高值

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