所以我有一张表,让我们说两列。
Owner | Letter |
------|--------|
John | A |
John | B |
John | B |
Bob | B |
Sam | A |
Sam | B |
我正在尝试计算字母列并由所有者分组。我想最终得到拥有最独特字母的人。 像这样:
Owner | Count |
----------------
John | 2 |
Sam | 2 |
我可以统计所有按照所有者分组的信件,但每当我尝试使用max时,似乎都无法将它们组合在一起。
这是我到目前为止所做的:
select owner
from table
where (select count(distinct letter) from table group by owner) in
(select max(count(distinct letter)) from table group by owner);
这个查询当然不起作用,因为我正在比较两个选择语句,我似乎无法弄清楚我应该朝哪个方向前进。任何帮助将非常感谢。感谢。
答案 0 :(得分:1)
答案 1 :(得分:0)
with t as (
select owner,count(distinct letter) dl
from table
group by owner)
select t.*
from t
where (owner,dl) IN
(select owner, max(dl) from t group by owner);
答案 2 :(得分:0)
我会使用GROUP BY
,HAVING
和all
运算符
SELECT owner, COUNT(distinct letter)
FROM your_table
GROUP BY owner
HAVING COUNT(distinct letter) >= ALL
(
SELECT COUNT(distinct letter)
FROM your_table
GROUP BY owner
)