假设我有一个包含三列的表格key
,value
和priority
,其中包含一个唯一键(key
,priority
)。< / p>
我想选择所有key
/ value
对,其中该密钥的priority
高于同一key
的任何其他优先级。
例如:
key | value | priority
----------------------
'a' | 'Alice' | 5
'a' | 'Aaron' | 10
'b' | 'Bob' | 1
应该返回:
key | value
-------------
'a' | 'Aaron'
'b' | 'Bob'
编写此类查询的有效方法是什么?
答案 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