Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Return most occurance of specific item in list

Author  Topic 

RobertWhite001
Starting Member

1 Post

Posted - 2009-04-21 : 16:32:13

Strange question. I am new at SQL and would think there would be an easy way to do this. Lets say I have two tables one named customers (primary key CustomerID), one table porducts (primary key productID), and one table orders that has the OrderID, CustomerID, and ProductID field. From that I want to return all the products and the customer who ordered the most of that product.

Here is a sample:
Product Customer
Apples Jim
Apples Jim
Apples Jim
Apples Tom
Apples Tom
Peach Tom
Peach Tom
Peach Tom
Peach Jim

Expected Results

Product Customer who orders most
Apples Jim
Peach Tom

There will be thousands of products and customers.
Thanks in advance!

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2009-04-21 : 17:25:44
Here is one way:
DECLARE @Customer TABLE (CustomerID INT PRIMARY KEY, CustomerName VARCHAR(50))
INSERT @Customer
SELECT 1, 'Jim'
UNION ALL SELECT 2, 'Tom'

DECLARE @Product TABLE (ProductID INT PRIMARY KEY, ProductName VARCHAR(50))
INSERT @Product
SELECT 1, 'Apple'
UNION ALL SELECT 2, 'Peach'

DECLARE @Order TABLE (OrderID INT, CustomerID INT, ProductID INT)
INSERT @Order
SELECT 1, 2, 1
UNION ALL SELECT 1, 2, 1
UNION ALL SELECT 1, 2, 1
UNION ALL SELECT 1, 1, 1
UNION ALL SELECT 1, 1, 1
UNION ALL SELECT 1, 1, 2
UNION ALL SELECT 1, 1, 2
UNION ALL SELECT 1, 1, 2
UNION ALL SELECT 1, 2, 2




SELECT
ProductName,
CustomerName
FROM
(
SELECT
ProductName,
CustomerName,
ROW_NUMBER() OVER (PARTITION BY P.ProductName ORDER BY COUNT(*) DESC) AS RowNum
FROM
@Order AS O
INNER JOIN
@Customer AS C
ON O.CustomerID = C.CustomerID
INNER JOIN
@Product AS P
ON O.ProductID = P.ProductID
GROUP BY
P.ProductName,
C.CustomerName
) AS T
WHERE
T.RowNum = 1
Go to Top of Page
   

- Advertisement -