我需要获取在特定月份首次订购特定产品的客户列表,然后汇总他们从那时起订购的商品数量。我开始研究这个问题,但感觉我走向了错误的方向 - SQL不是我的强项。
因此,样本结果数据将类似于:
Num of Customers | Num of Orders | Total Revenue | Total Gross Profit
--------------------------------------------------------------------------
January 100 135 $1350 $725
以下是我的表格(不需要排除的列):
CustomerID
CustomerOrderID
客户ID
订单ID
订购日期
CustomerOrderItemID
订单ID
SKU
价格
成本
示例SKU类似于“ESK-1MVV”,利润只是价格 - 成本
答案 0 :(得分:1)
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'
限制购买商品的客户,并获取他们首次购买商品的日期。在外面的地方,限制在所需的月份首先购买它的人。添加“和OrderDate> firstDate”以排除第一笔销售,如果这是您想要的