tags:

views:

55

answers:

1

I need to get a list of customer who ordered a particular product for the first time in a particular month and then sum how much of that items they have ordered since then. I started working on this but feel like I am going in the wrong direction - SQL is not my strong point.

So sample result data would be something like:

              Num of Customers   |  Num of Orders | Total Revenue | Total Gross Profit 
--------------------------------------------------------------------------
January       100                   135              $1350           $725

Here are my tables (excluded columns not needed):

Customer

CustomerID

CustomerOrder

CustomerOrderID
CustomerID
OrderID
OrderDate

CustomerOrderItem

CustomerOrderItemID
OrderID
SKU
Price
Cost

Sample SKU would be something like 'ESK-1MVV' and profit is simply Price - Cost

+1  A: 
select count(c.CustomerID), sum(Price), sum((Price-Cost)) 
from  
(
  select CustomerID, min(OrderDate) as firstDate
  From CustomerOrder a
  inner join CustomerOrderItem b
  on a.OrderID = b.OrderID
  where SKU='ESK-1MVV'
  group by CustomerID
) as firstSale
inner join
CustomerOrder c
on firstSale.CustomerID = c.CustomerID
inner join CustomerOrderItem d
on c.OrderID = d.OrderID
where month(firstSale.firstDate) = 1
and year(firstSale.firstDate) = 2009
and d.SKU='ESK-1MVV'

Limit to the customers who bought the item, and get the date they first bought it. In the outer where, limit to ones who bought it first in the desired month. Add "and OrderDate > firstDate" to exclude the first sale, if that's what you wanted

ansate
LOL - I was going about this so wrong - as soon as I was min(OrderDate) How would I get the Total Order count?
Slee
that count(CustomerID) in the select should be doing it - there's only one row per order of that item now - and each row has a non-null CustomerIDIf you want one row out for each customer (I read it as totals for all custs who bought for the first time in Jan), I think you can throw a "Group by c.CustomerID" onto the end
ansate
I need a CustomerCount AND and an OrderCount - a single customer could have ordered that product every month since January - make sense?
Slee
OOOO. each row is an SKU? select count(distinct(c.CustomerID)), count(c.CustomerID), sum(Price), sum((Price-Cost))
ansate