Can there be a database-agnostic SQL query to fetch top N rows?

后端 未结 5 849
有刺的猬
有刺的猬 2021-01-28 05:33

We want to be able to select top N rows using a SQL Query. The target database could be Oracle or MySQL. Is there an elegant approach to this? (Needless to say, we\'re dealing w

5条回答
  •  粉色の甜心
    2021-01-28 06:15

    To get the top 5 scorers from this table:

    CREATE TABLE people
                 (id      int, 
                  name    string, 
                  score   int)
    

    try this SQL:

    SELECT id, 
           name, 
           score
    FROM   people  p
    WHERE  (SELECT COUNT(*) 
            FROM   people p2
            WHERE  p2.score  > p.score 
           ) <=4 
    

    I believe this should work in most places.

提交回复
热议问题