[英]How to do MAX COUNT so Query returns 1 Result SQL
I have the following query:我有以下查询:
SELECT
Id,
EmailDomain,
COUNT(Users) AS UserCount
FROM
Table_Moragn
GROUP BY
Id, EmailDomain
Which returns the following results:返回以下结果:
Id ![]() |
EmailDomain![]() |
UserCount![]() |
---|---|---|
1 ![]() |
@yahoo.com ![]() |
1 ![]() |
1 ![]() |
@gmail.com ![]() |
4 ![]() |
2 ![]() |
@hotmail.com ![]() |
1 ![]() |
3 ![]() |
@aol.com ![]() |
1 ![]() |
3 ![]() |
@comcast.com ![]() |
1 ![]() |
I need the Ids and the Email Domains for a later query, but I don't want multiple email domains.我需要 ID 和电子邮件域以供以后查询,但我不想要多个电子邮件域。 So I want my results to look like this:
所以我希望我的结果是这样的:
Id ![]() |
EmailDomain![]() |
UserCount![]() |
---|---|---|
1 ![]() |
@gmail.com ![]() |
4 ![]() |
2 ![]() |
@hotmail.com ![]() |
1 ![]() |
Original I thought to do a Max Count either through a subquery or having by原来我想通过子查询或通过
SELECT
Id,
EmailDomain,
COUNT(Users) AS UserCount
FROM
Table_Morgan
GROUP BY
Id, EmailDomain
HAVING
COUNT(Users) = (SELECT MAX(UserCount)
FROM (EmailDomain, COUNT(Users) as UserCount
FROM Table_Morgan
GROUP BY EmailDomain) AS T)
but I get an error但我收到一个错误
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS
当子查询没有用EXISTS引入时,select列表中只能指定一个表达式
Or says it can't return multiple results with an =.或者说它不能用 = 返回多个结果。
A problem I see with this in cases like ID 3, where the count is the same number.我在 ID 3 等情况下看到的一个问题,其中计数是相同的数字。
I tried adding LIMIT at the end of my query but SQL doesn't like it.我尝试在查询的末尾添加 LIMIT,但 SQL 不喜欢它。
Use Dense_Rank()
windowed function to display tied rank as well.使用
Dense_Rank()
窗口函数也可以显示绑定等级。
SELECT -- main result
*
FROM (SELECT -- ranking here
*,
DENSE_RANK() OVER (PARTITION BY Id ORDER BY UserCount DESC, EmailDomain) rnk
FROM (SELECT -- group count here
Id,
EmailDomain,
COUNT(Users) AS UserCount
FROM Table_Moragn
GROUP BY Id,
EmailDomain) x) y
WHERE y.rnk = 1
You can use MAX()
and FIRST_VALUE()
window functions in your query:您可以在查询中使用
MAX()
和FIRST_VALUE()
窗口函数:
SELECT DISTINCT Id,
FIRST_VALUE(EmailDomain) OVER (PARTITION BY Id ORDER BY COUNT(Users) DESC) EmailDomain,
MAX(COUNT(Users)) OVER (PARTITION BY Id) UserCount
FROM Table_Moragn
GROUP BY Id, EmailDomain;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.