你好我是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
答案 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;