我的数据库中有这些数据。
id | company_id | referrer
001 | 001 | https://google.com
002 | 001 | https://riot.com
003 | 001 | https://google.com
004 | 002 | https://vimeo.com
005 | 002 | https://yahoo.com
006 | 003 | https://yahoo.com
我想得到每个company_id的推荐人重复的次数。一家公司有很多推荐人,但我只想得到数据中重复的最高推荐人。
所以结果会是这样的:
company_id | referrer | nRepeat
001 | https://google.com | 2
002 | https://yahoo.com | 2
我试过这个代码:
SELECT company_id,
referrer,
Count(referrer) AS viewCount
FROM `my_table`
GROUP BY company_id
ORDER BY viewcount DESC
这个查询似乎是错误的。
如果我解释得不好,我深表歉意,如果你有问题,请告诉我。
有什么建议或帮助吗?非常感谢您的帮助!谢谢
我们可以在这里使用RANK
:
WITH cte AS (
SELECT company_id, referrer, COUNT(*) viewCount,
RANK() OVER (PARTITION BY company_id ORDER BY COUNT(*) DESC) rnk
FROM my_table
GROUP BY company_id, referrer
)
SELECT company_id, referrer, viewCount
FROM cte
WHERE rnk = 1;
这是上面写的一个单一的选择,没有使用CTE:
SELECT company_id, referrer, viewCount
FROM
(
SELECT company_id, referrer, COUNT(*) viewCount,
RANK() OVER (PARTITION BY company_id ORDER BY COUNT(*) DESC) rnk
FROM my_table
GROUP BY company_id, referrer
) t
WHERE rnk = 1;
以下是一个应该在8+之前的MySQL版本上工作的版本:
SELECT company_id, referrer, COUNT(*) viewCount
FROM my_table t1
GROUP BY company_id, referrer
HAVING COUNT(*) = (SELECT COUNT(*)
FROM my_table t2
WHERE t2.company_id = t1.company_id
GROUP BY referrer
ORDER BY COUNT(*) DESC
LIMIT 1);