![](/img/trans.png)
[英]Select only one value from a column for each value in another column, together with corresponding other columns value
[英]Nested SQL Selects? DISTINCT from one column, and get the corresponding Mode for each value in another?
所以說我有一個名為Key_Values的表,看起來像
--keys--|--values--
A | 1
A | 1
A | 2
B | 1
B | 1
C | 3
C | 3
C | 4
我需要編寫一個選擇語句,該語句將獲取所有不同的鍵及其各自的值模式。 它會返回這個
--keys--|--values--
A | 1
B | 1
C | 3
我在找出正確的方法時遇到了一些麻煩。 我知道我可以執行DISTINCT(keys),但是我不確定如何從中獲取值。
如果數據庫支持,則可以使用窗口函數:
select key, value as mode
from (select key, value, count(*) as cnt,
row_number() over (partition by key order by count(*) desc) as seqnum
from keyvalue
group by key, value
) kv
where seqnum = 1;
在MS Access中,這要痛苦得多:
select key, value, count(*) as cnt
from keyvalue kv
group by key, value
having kv.value = (select top (1) kv2.value
from keyvalue kv2
where kv2.key = kv.key
group by kv2.value
order by count(*) desc
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.