我正在尝试编写一个SQL查询,在那里我找到最常出现的值。
到目前为止,我有这个:
SELECT GENRE, COUNT(*) AS Frequency
FROM BooksRead
GROUP BY GENRE
这给了我这样的输出:
Anthropological 1
Biography 7
Crime 4
Essay 2
我希望返回的结果为7.我尝试使用TOP 1,但我的Java编译器似乎不喜欢它。
答案 0 :(得分:1)
ANSI SQL语法为:
SELECT GENRE, COUNT(*) AS Frequency
FROM BooksRead
GROUP BY GENRE
ORDER BY COUNT(*) DESC
FETCH FIRST 1 ROW ONLY;
并非所有数据库都支持该语法。许多人支持LIMIT
:
SELECT GENRE, COUNT(*) AS Frequency
FROM BooksRead
GROUP BY GENRE
ORDER BY COUNT(*) DESC
LIMIT 1;
但是,确切的语法取决于您使用的数据库。
您还可以使用ANSI标准窗口函数:
SELECT *
FROM (SELECT GENRE, COUNT(*) AS Frequency,
ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC) as seqnum
FROM BooksRead
GROUP BY GENRE
) g
WHERE seqnum = 1;
如果您想要关联,请使用RANK()
代替ROW_NUMBER()
。