sql查询与count混淆

时间:2016-04-26 09:23:08

标签: mysql postgresql

我试图从正在阅读的sql书中找出这个查询。

  1. 根据提供课程的次数查找最受欢迎课程的名称。
  2. 我有查询,如果它列出了课程,并计算每个提供了多少次,现在我的问题是如何满足上面的问题大声笑。我怎样才能获得最多提供的课程? (即数据库课程)

    我的查询是

    SELECT
        count(s.course_id) AS Times_Offered,
        c.title
    FROM
        sections s
    INNER JOIN courses c ON c.id = s.course_id
    GROUP BY    c.title
    ORDER BY    Times_Offered DESC;
    

    我的查询显示为

    times_offered   title
         3        Databases
         3        Calculus 1
         2        Compilers
         2        Elocution
         2        Acting
         1        Topology
    

2 个答案:

答案 0 :(得分:1)

如果你想要最受欢迎的课程,你需要获得所有最大的课程。这将给出你期望的答案。

SELECT 
count(s.course_id) AS Times_Offered,
c.title
FROM
sections s
INNER JOIN courses c ON c.id = s.course_id
GROUP BY    c.title
ORDER BY    Times_Offered DESC
Having Times_Offered =
SELECT max(t1.Times_offered) from
(SELECT 
count(s.course_id) AS Times_Offered,
c.title
FROM
sections s
INNER JOIN courses c ON c.id = s.course_id
GROUP BY    c.title
ORDER BY    Times_Offered DESC) t1

你的答案应该是

times_offered   title
 3        Databases
 3        Calculus 1

答案 1 :(得分:0)

如果您想对它们进行计数,然后只显示编号最高的那个,请尝试:

SELECT COUNT(s.course_id) 
AS Times_Offered, c.title FROM sections s 
INNER JOIN courses c ON c.id=s.course_id 
GROUP BY c.title 
ORDER BY Times_Offered DESC
LIMIT 1