Select Max of sum

  • I want to get the maximum of sum with one select statement.

    The database is NorhtWind and this is the query.

    select orderid, sum(quantity)

    from [order details]

    where orderid between 11000 and 11005

    group by orderid

    order by 2 desc

    I know that i can use this statement:

    select Top 1 orderid, sum(quantity)

    from [order details]

    where orderid between 11000 and 11005

    group by orderid

    order by 2 desc

    or to use temporery tables but i am interested is there any different way to get only one row with maximum sum per orderid.

    thanks

    Alex

  • what about select max(sum(quantity)) from  ...

    cheers

    dbgeezer

  • select max(qty) from (

    select orderid, qty = sum(quantity)

    from [order details]

    where orderid between 11000 and 11005

    group by orderid

    ) a


    -- Amit



    "There is no 'patch' for stupidity."



    Download the Updated SQL Server 2005 Books Online.

  • THANKS Amit

    That is what i wanted, but how can i see and order id for maximum sum.

    Alex

  • Try this:-

    SELECT c.OrderId, b.[Max Qty]

    FROM

    (SELECT MAX(Qty) AS [Max Qty]

    FROM

    (SELECT OrderId, SUM(Quantity) AS Qty

    FROM [Order Details]

    WHERE OrderId BETWEEN 11000 AND 11005

    GROUP BY OrderId) a) b

    INNER JOIN

    (SELECT OrderId, SUM(Quantity) AS Qty

    FROM [Order Details]

    WHERE OrderId BETWEEN 11000 AND 11005

    GROUP BY OrderId) c

    ON b.[Max Qty] = c.Qty

    Might be an easier way tho., but it works.

  • thanks a lot

    alex

Viewing 6 posts - 1 through 5 (of 5 total)

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