所以说我有一个名为Key_Values的表,看起来像
--keys--|--values--
A | 1
A | 1
A | 2
B | 1
B | 1
C | 3
C | 3
C | 4
我需要编写一个select语句,该语句将获取所有不同的键以及它们各自的值的模式。它将返回此
--keys--|--values--
A | 1
B | 1
C | 3
我在找出正确的方法时遇到了一些麻烦。我知道我可以执行DISTINCT(keys),但是我不确定如何从中获取值。
答案 0 :(得分:1)
如果数据库支持,则可以使用窗口函数:
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
);