sql >> Database teknologi >  >> RDS >> Mysql

Hvordan skriver man denne SQL-sætning?

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

rediger Dette fungerer muligvis bedre, afhængigt af det RDBMS, du bruger, og størrelsen af ​​datasættet. Prøv begge dele og sammenlign.

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


  1. Hvordan sender man e-mail fra SQL Server?

  2. Driver JDBC PostgreSQL med Android

  3. MySql Last Insert ID, Connector .net

  4. Dynamisk SQL til at generere kolonnenavne?