Results 1 to 3 of 3

Thread: [RESOLVED] SQL SERVER 2005 - Top clause

  1. #1

    Thread Starter
    Hyperactive Member Ms.Longstocking's Avatar
    Join Date
    Oct 2006
    Posts
    399

    Resolved [RESOLVED] SQL SERVER 2005 - Top clause

    Say I have 5 records in a table.

    tableSample(username, color, total)

    wendy blue 6
    josh yellow 9
    brad topaz 3
    lily green 4
    candy teal 11


    now, I wish to select the user with the highest value.
    In this case, I want Candy.

    Code:
    SELECT TOP 1 * from tableSample
    order by total Desc

    All good?


    now, let's say that 2 or more users share the same top value?

    wendy blue 6
    josh yellow 9
    brad topaz 11
    lily green 4
    candy teal 11


    Would the following be the proper way to display brad and candy?:

    Code:
    DECLARE @highest tinyint
    SET @highest = (SELECT MAX(total) from tableSample)
    SELECT * FROM tableSample
    WHERE total = @highest

  2. #2
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: SQL SERVER 2005 - Top clause

    You don't need to create a variable, you can use the Max query directly as a sub-query:
    Code:
    SELECT * 
    from tableSample
    WHERE total = (SELECT Max(total) FROM tableSample)

  3. #3

    Thread Starter
    Hyperactive Member Ms.Longstocking's Avatar
    Join Date
    Oct 2006
    Posts
    399

    Re: SQL SERVER 2005 - Top clause

    I see that.
    I simply wished to make sure that I wasn't overlooking something in SQL

    Looks good.
    Thanks si.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width