Select distinct top 5 column1 from table order by column2 desc

  • I have to get top 5 distinct salesid from the table order by dealid desc.The Dealid is a ever increasing number.

    My query output should be as shown below and this salesid will be used in where clause of another query.

    salesid

    12

    78

    11

    356

    63

  • DECLARE @temp TABLE (

    RowId INT IDENTITY

    , SalesId INT

    )

    INSERT INTO @temp (

    SalesId

    )

    SELECT Salesid

    FROM temp

    ORDER BY dealid DESC

    SELECT TOP 5 t.SalesId

    FROM @temp t

    INNER JOIN (

    SELECT SalesId, MIN(RowId) AS RowId

    FROM @temp

    GROUP BY SalesId

    ) x ON t.RowId = x.RowId

    ORDER BY x.RowId

    Depending on relationship between SalesId and DealId, you could also group by Sales and then order by the sum(DealId) desc and take top 5 that way.

    _____________________________________________________________________
    - Nate

    @nate_hughes

Viewing 2 posts - 1 through 1 (of 1 total)

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