如何计算 SQL 中派生表的出现次数?

joh*_*987 0 mysql derived-table

我有这个非常简单的表:

CREATE TABLE MyTable 
( 
    Id INT(6) PRIMARY KEY,
    Name VARCHAR(200) /* NOT UNIQUE */
); 
Run Code Online (Sandbox Code Playgroud)

如果我想要最常见的名称和相应的计数,我既不能这样做

SELECT Name, total
FROM table2
WHERE total = (SELECT MAX(total) FROM (SELECT Name, COUNT(*) AS total
                                       FROM MyTable GROUP BY Name) table2);
Run Code Online (Sandbox Code Playgroud)

也不是这个

SELECT Name, total
FROM (SELECT Name, COUNT(*) AS total FROM MyTable GROUP BY Name) table1
WHERE total = (SELECT MAX(total) FROM table1);
Run Code Online (Sandbox Code Playgroud)

另外,(假设最大计数为 4)在第二个命题中,如果我将第三行替换为

WHERE total = 4;
Run Code Online (Sandbox Code Playgroud)

有用。
为什么会这样?

多谢

Dim*_*imi 5

您可以尝试以下操作:

WITH stats as
(
SELECT Name
      ,COUNT(id) as count_ids
FROM MyTable
GROUP BY Name
)

SELECT Name
      ,count_ids
FROM
(
SELECT Name
      ,count_ids
      ,RANK() OVER(ORDER BY count_ids DESC) as rank_ -- this ranks all names
FROM stats
) s
WHERE rank_ = 1 -- the most popular ```

This should work in TSQL.
Run Code Online (Sandbox Code Playgroud)