[英]Occurrence of the most frequent value in mysql
I am stuck on a problem where I need to find the count of the most frequent value.我遇到了一个问题,我需要找到最常见值的计数。
With this I will get the Table with all the different cars, their problem count and the most frequent problem.有了这个,我将得到所有不同汽车的表格,它们的问题数量和最常见的问题。
Now I want to count how many times does the most frequent problem occur.现在我想计算最常见的问题发生了多少次。 I think I need to do something with subqueries but I can't seem to figure it out.
我想我需要对子查询做一些事情,但我似乎无法弄清楚。
Can anyone help me out or lead me to the right direction please?任何人都可以帮助我或引导我走向正确的方向吗?
Did I get you right, that you would like to count the occurence of the most frequent ProblemCount?我说得对吗,您想计算最常见的 ProblemCount 的出现吗?
If so: This is not the cleanest solution, but I hope, this will help you.如果是这样:这不是最干净的解决方案,但我希望这会对您有所帮助。
SELECT
ProblemCount,
COUNT(ProblemCount)
FROM(
SELECT Cars.Model,
COUNT(Jobs.JobType) AS ProblemCount,
Jobs.JobType AS MostCommonProblemType
FROM Cars
INNER JOIN Jobs ON Jobs.CarId = Cars.Id
GROUP BY Cars.Model
) A
WHERE ProblemCount = (SELECT MAX(B.ProblemCount) FROM (SELECT
COUNT(Jobs.JobType) AS ProblemCount
FROM Cars
INNER JOIN Jobs ON Jobs.CarId = Cars.Id
GROUP BY Cars.Model) B)
GROUP BY ProblemCount;
The best solution is to use a window function, rank()
:最好的解决方案是使用 window function,
rank()
:
SELECT *
FROM (SELECT c.Model, COUNT(*) AS ProblemCount,
j.JobType AS MostCommonProblemType,
RANK) OVER (PARTITION BY c.Model ORDER BY COUNT(*) DESC) as ranking
FROM Cars c INNER JOIN
Jobs j
ON j.CarId = c.Id
GROUP BY c.Model, j.JobType
) m
WHERE ranking = 1;
Here is a db<>fiddle. 这是一个 db<>fiddle。
Note that use a table aliases;注意使用表别名; this makes the query easier to write and to read.
这使查询更易于编写和阅读。 Also, you can use
COUNT(*)
.此外,您可以使用
COUNT(*)
。 There seems to be no need to check if Job(JobType)
is not NULL
, which is what COUNT(j.JobType)
does.似乎没有必要检查
Job(JobType)
是否不是NULL
,这就是COUNT(j.JobType)
所做的。
I used, as you, that strange feature of mysql, using a column that is not grouped and not aggregated, and made the needed subselect:像你一样,我使用了 mysql 的奇怪功能,使用未分组且未聚合的列,并进行了所需的子选择:
SELECT c.Model,
COUNT(j.JobType) AS ProblemCount,
j.JobType as MostCommonProblemType
, (select count(*) from Jobs where jobs.Jobtype = j.JobType
and CarId in (select Id from Cars c2 where c2.model = c.model)
) as ProblemCount
FROM Cars c
INNER JOIN Jobs j ON j.CarId = c.Id
GROUP BY c.Model
ORDER BY COUNT(j.JobType) DESC;
Output Output
Model ![]() |
ProblemCount![]() |
MostCommonProblemType![]() |
ProblemCount![]() |
---|---|---|---|
Ford Mustang![]() |
8 ![]() |
Engine![]() |
4 ![]() |
Ford Focus![]() |
6 ![]() |
Engine![]() |
3 ![]() |
Ford Puma![]() |
2 ![]() |
Maintenance![]() |
2 ![]() |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.