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

Valg af største N poster i X grupper

SELECT catX.category
       catX.interest
       t1.user_id
       t1.score
FROM 
    ( SELECT category 
           , interest 
      FROM tableX 
      WHERE user_id = @user_id_we_are_interested_in     --- specific user 
      ORDER BY interest DESC
      LIMIT @X                         --- top @X categories per specific user 
    ) AS catX 
  JOIN 
    tableX AS t1 
      ON t1.category = catX.category 
  LEFT JOIN 
    tableX AS t2 
      ON  t2.category = t1.category 
      AND t2.score > t1.score 
  GROUP BY t1.category
         , t1.user_id
  HAVING COUNT(t2.score) < @N                      --- top @N users per category 
  ORDER BY catX.interest DESC 
         , t1.score DESC 


  1. SQL Server:kombination af flere rækker til en række

  2. Hvordan redigerer man en lagret procedure i MySQL?

  3. PostgreSQL:Ufølsom streng sammenligning

  4. Hvordan håndterer man flere opslagstabeller for begyndere med SQL?