admin

怎么写这个SQL语句?

sql

下表是:用户

Name:  Subject:
Peter   Math
Mary    Chinese
Mary    Computer
Mary    Hist
Mary    PE
Mary    English
Peter   Art
Chris   English
Chris   Computer
Peter   Computer
Paul    Math

我想让顶部出现在名称中,并返回前4个结果应该是使用者名称。例如,在这种情况下,最上面出现的名称是Mary,并且基于主题(中文,计算机,英语)的顺序,因此我希望得到以下结果:

Mary    Chinese
Mary    Computer
Mary    English
Mary    Hist

如果Mary不足以显示结果,那么第二个人将是跟随者,例如,假设表将如下所示:

Name:  Subject:
Peter   Math
Mary    Chinese
Mary    Computer
Mary    Hist
Peter   Art
Chris   English
Chris   Computer
Peter   Computer
Paul    Math

结果将是

Mary    Chinese
Mary    Computer
Mary    Hist
Peter   Art

因为玛丽是出现次数最多的人,所以玛丽会返回,但玛丽不足以填补4个职位,因此,第二出现次数最多的地方将是该位置,在这种情况下,我们使用彼得。


阅读 338

收藏
2021-06-07

共1个答案

admin

SELECT user.name, user.subject
FROM user
INNER JOIN (
    SELECT name, COUNT(1) AS occurrences
    FROM user
    GROUP BY name
  ) AS user_occurrences
  ON user.name = user_occurrences.name
ORDER BY user_occurrences.occurrences DESC, user.name ASC, user.subject ASC
LIMIT 4

编辑 这可能会更好,具体取决于您使用的RDBMS和数据集的大小。尝试两者并进行比较。

SELECT user.name, user.subject
FROM user
INNER JOIN user AS user_occurrences
  ON user.name = user_occurrences.name
GROUP BY user.name --, user.subject Second GROUP BY not needed on MySQL, but it should logically be there
ORDER BY COUNT(user_occurrences.subject) DESC, user.name ASC, user.subject ASC
LIMIT 4
2021-06-07