在GROUP BY查询中查找最高COUNT

时间:2017-03-30 21:31:53

标签: sql postgresql count group-by

你好我是postgresql的新手。这是我的代码,用于对选项进行分组并对其进行计数。我想要一种方法来获得最大计数的选项。有什么办法吗?

SELECT s.option, COUNT(*)
FROM "Set" as s, "Lecture" as l, "Process" as p, "donation" as d
WHERE d.code = p.code and l.type = p.type and l.option = s.option
GROUP BY s.option

2 个答案:

答案 0 :(得分:0)

只需为孩子命名(例如count),ORDER BY该名称,LIMIT为1:

SELECT s.option, COUNT(*) AS count -- give the child a name
FROM "Set" as s, "Lecture" as l, "Process" as p, "donation" as d
WHERE d.code = p.code and l.type = p.type and l.option = s.option
GROUP BY s.option
ORDER BY count DESC -- order by that child in descending order
LIMIT 1 -- and limit the output to one row

如果您想要最高,则应将DESC添加到ORDER BY。如果你想要最低;要么不指定,要么添加ASC

答案 1 :(得分:0)

您可以简化查询。不仅可以使用PROPER,显式JOIN语法,还可以删除Set

SELECT l.option, COUNT(*)
FROM "Lecture" l JOIN
     "Process" p
     ON l.type = p.type JOIN
     "donation" d
     ON d.code = p.code
GROUP BY l.option
ORDER BY COUNT(*) DESC
FETCH FIRST 1 ROW ONLY;