help using the TOP command in sql

  • I guess it depends, is it a take home test?

  • Mish,

    Back to your original question (how to use TOP to get the second and third rows of a result set). Have you tried my suggestion of using TOP in the WHERE clause?

    I'll give a bit more of a hint: you want to return the first two rows (numbers 3 and 4) with key values greater than the larger of the first two rows overall (rows 1 and 2). So, your query would ask for ... the TOP 2 (ordered by key) -- Rows 3 and 4

    where the key is greater than

    [Select the max(key) in the TOP 2 Key Ordered by Key] (the StartPoint) -- key of row 2I've not stated this in exactly the same way your SQL would be coded in order to give you a chance to study and understand it. Try translating this "pseudo-code" to T-SQL and I'm sure plenty of people here will help you with any glitches you have with it. One gotcha to keep in mind: the subquery does need to be given an alias (the "StartPoint" in the pseudo code).

  • Thanks John for the help. I have managed to get an answer to my original question and I now know that SQL does not have a command similar to LIMIT in Mysql and that I would have to use a much more complex query in order to return the results in a larger database.

  • mish (8/14/2009)


    Thanks John for the help. I have managed to get an answer to my original question and I now know that SQL does not have a command similar to LIMIT in Mysql and that I would have to use a much more complex query in order to return the results in a larger database.

    Well, you've got my curiosity up. And it may be helpful for others who find this discussion to know what your answer is. Could you please post it?

  • It's not all that complex.

    A cte with row_number(), read by a WHERE clause using BETWEEN should get the job done.

    __________________________________________________

    Against stupidity the gods themselves contend in vain. -- Friedrich Schiller
    Stop, children, what's that sound? Everybody look what's going down. -- Stephen Stills

  • something like;

    Select Top(2) XXXXXX from (Select 4 XXXXX from YYYYY order by XXXX Desc)

Viewing 6 posts - 16 through 20 (of 20 total)

You must be logged in to reply to this topic. Login to reply