在当月和上个月购买商品的CustomerID

时间:2018-08-31 15:28:40

标签: sql-server

我在处理此查询时遇到麻烦。我有一个存储客户ID和日期项目购买的表,如下所示(这是我试图获取的结果):

REST_FRAMEWORK = {
    'UNICODE_JSON': False,
}

我正在尝试创建一个月度报告,如果他们在上个月购买了商品,我还希望列出customerID。

CustomerID  PurchaseDate
------------------------
1              08/10/2018
1              07/15/2018
2              08/15/2018
2              08/15/2018

我试图获取上面的结果,以将上个月的customerid 1包含进来。我尝试添加以下内容,但会得到列表

select CustomerId, PurchaseDate 
From Orders
Where PurchaseDate between '08/01/18' and '08/31/18' --- can't be changed

但是这将包括上个月购买的客户和物品清单,即使他们当月没有购买任何物品。有什么建议吗?我将很高兴地对此表示赞赏。谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用EXISTS:

select CustomerId, PurchaseDate 
From Orders o
Where PurchaseDate between '08/01/18' and '08/31/18'
 AND EXISTS (select *
             From Orders o1
             Where PurchaseDate between '07/01/18' and '07/31/18'
               and o.CustomerId = o1.CustomerId)

-

编辑:

您应该使用JOIN,然后:

SELECT o1.CustomerId, o1.PurchaseDate, o2.PurchaseDate
FROM Orders o1
JOIN Orders o2
  ON o1.CustomerId = o2.CustomerId
Where o1.PurchaseDate between '08/01/18' and '08/31/18'
  AND o2.PurchaseDate between '07/01/18' and '07/31/18'