**castID**
nm0000116
nm0000116
nm0000116
nm0000116
nm0000116
nm0634240
nm0634240
nm0798899
这是我的表(作为视图创建)。现在我想列出计数最多的castID(在这种情况下是nm0000116,它在这个表中有多少次出现/计数(应该是5次)而且我不太确定要使用哪个查询
答案 0 :(得分:1)
SELECT
MAX(E),
castId
FROM
(SELECT COUNT(castId) AS E,castId FROM [directors winning movies list] GROUP BY castId) AS t
答案 1 :(得分:1)
试
Select CastId, count(*) countOfCastId
From table
Group By CastId
Having count(*)
= (Select Max(cnt)
From (Select count(*) cnt
From table
Group By CastId) z)
答案 2 :(得分:0)
您可以使用LIMIT
返回最顶层的计数:
SELECT castID,
COUNT(*) AS Cnt
FROM atable
GROUP BY castID
ORDER BY Cnt DESC
LIMIT 1
;
但是,如果可以存在关联,则上述查询将只返回一行。如果您想要所有"获胜者",您可以将上述查询中的计数作为标量结果,并将其与所有计数进行比较,以仅返回匹配的计数:
SELECT castID,
COUNT(*) AS Cnt
FROM atable
GROUP BY castID
HAVING COUNT(*) = (
SELECT COUNT(*)
FROM atable
GROUP BY castID
ORDER BY Cnt DESC
LIMIT 1
)
;
(基本上与Charles Bretana's approach相同,它只是以不同的方式得出最高计数。)
或者,您可以使用变量对所有计数进行排名,然后仅返回排名为1的计数:
SELECT castID,
Cnt
FROM (
SELECT castID,
COUNT(*) AS Cnt,
@r := IFNULL(@r, 0) + 1 AS r
FROM atable
GROUP BY castID
ORDER BY Cnt DESC
) AS s
WHERE r = 1
;
请注意,使用上述方法,变量必须不存在或在运行查询之前使用0或NULL进行预初始化。为安全起见,您可以直接在查询中初始化变量:
SELECT s.castID,
s.Cnt
FROM (SELECT @r := 0) AS x
CROSS JOIN
(
SELECT castID,
COUNT(*) AS Cnt,
@r := @r + 1 AS r
FROM atable
GROUP BY castID
ORDER BY Cnt DESC
) AS s
WHERE s.r = 1
;