当前月份和上个月的CustomerID和订单日期列表

时间:2018-09-10 16:14:04

标签: sql-server

我在处理此查询时遇到麻烦。我有一个存储客户ID和购买的表格,如下所示:

CustomerID  PurchaseDate
------------------------
1              09/10/2018
1              08/15/2018
2              09/05/2018
2              09/07/2018
3              09/02/2018
4              08/20/2018

我正在尝试创建一个月度报告,其中显示当月的客户ID和购买价格,如果他们购买了商品,还显示前一个月的购买价格。

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

因为这将包括上个月购买的客户和项目的清单,即使他们当月没有购买任何商品。我可以使用临时表存储每个月的customerID和purchateate,然后将它们连接在一起,但是我试图在不使用临时表的情况下做到这一点。这就是我想要得到的结果。

CustomerID  PurchaseDate
------------------------
1              09/10/2018
1              08/15/2018 ------ purchased previous month 
2              09/05/2018
2              09/07/2018
3              09/02/2018

有什么建议吗?我将很高兴地对此表示赞赏。谢谢!

2 个答案:

答案 0 :(得分:1)

以下是使用exists的一种选择:

select * 
from orders o
where exists (
    select 1
    from orders o2 
    where o.customerid = o2.customerid
        and o2.PurchaseDate between '09/01/18' and '09/30/18'
    ) and o.PurchaseDate between '08/01/18' and '09/30/18'

答案 1 :(得分:0)

您的代码应如下所示:

select Orders.CustomerId, Orders.PurchaseDate, c.PurchaseDate as previous_month
From Orders, (select CustomerId, PurchaseDate from Orders where PurchaseDate 
    between '08/01/18' and '08/31/18' ) as c
Where Orders.PurchaseDate between '09/01/18' and '09/30/18'
and Orders.CustomerId = c.CustomerId

这称为子查询,如果让它失控,可能会很慢。