查找postgresql中列中出现最大值的值集

时间:2013-07-16 10:15:33

标签: postgresql

打印在大多数课程中注册的学生的姓名和sid

登记

sid  class number

1     23
2     54
1     54
3     43
1     43
2     43

学生     sid sname


1    sagar
2    kiran
3    ravi
4    vishal

输出

sid   sname

1     sagar

2 个答案:

答案 0 :(得分:4)

学生分组注册,按计数和使用限制1:

select s.id, s.name
from student s
join enroll e on e.sid = s.id
group by s.id, s.name
order by count(*) desc
limit 1

请注意,您不需要选择 count(*) - 您可能只需引用即可。

答案 1 :(得分:1)

我认为这会对你有帮助

SELECT <column_name> FROM <table_name> WHERE <column_name>=
(SELECT <column_name>
 FROM (SELECT <column_name>, count(*) as cnt FROM <table_name> GROUP BY <column_name>) AS foo
 WHERE foo.cnt=(SELECT MAX(c) FROM (SELECT <column_name>,count(*) AS c FROM <column_name> GROUP BY <column_name>) AS bar)) limit 1