Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Double Aggregate

0 views
Skip to first unread message

HSalim

unread,
Nov 19, 2009, 10:13:46 AM11/19/09
to
Hi,

I am trying to get the max value in a range in a way that requires a double
aggregation.
For example, using Northwind,
from the resultset of this query:

select ProductName, OrderID, SUM(Quantity) from OrderDetails
group by ProductName, OrderID
order by ProductName, sum(quantity) Desc


I want to get the OrderID and quantity that ordered the most for a
ProductName
such that I get
Alice Mutton 10607 100
Aniseed Syrup 10540 60
Boston Crab Meat 10895 91
...

Thanks in advance
Habib

Plamen Ratchev

unread,
Nov 19, 2009, 11:57:38 AM11/19/09
to
Here is one method:

SELECT ProductID, OrderID, qty
FROM (
SELECT ProductID, OrderID, SUM(Quantity) AS qty,
ROW_NUMBER() OVER(PARTITION BY ProductID ORDER BY SUM(Quantity) DESC) AS rk
FROM [Order Details]
GROUP BY ProductId, OrderID) AS P
WHERE rk = 1
ORDER BY qty DESC;

--
Plamen Ratchev
http://www.SQLStudio.com

HSalim

unread,
Nov 19, 2009, 12:44:41 PM11/19/09
to
Thank you Plamen!


"Plamen Ratchev" <Pla...@SQLStudio.com> wrote in message
news:loidnevJHPth5ZjW...@speakeasy.net...

--CELKO--

unread,
Nov 22, 2009, 3:54:28 PM11/22/09
to
>> I want to get the order_id and quantity that ordered the most for a product_name <<

WITH P(product_name, order_id, qty_tot)
AS
(SELECT product_name, order_id, SUM(order_qty)
FROM Order_Details
GROUP BY product_name, order_id)

SELECT P1.*
FROM P AS P1
WHERE P1.qty_tot
= (SELECT MAX (P2.qty_tot)
FROM P AS P2
WHERE P1.product_name = P2.product_name);

This will handle ties. Get the totals in a CTE, then use it to find
the maximum total quantity.

0 new messages