Skip to content
Advertisement

Limiting records by included/excluded/null date ranges

First, a description of my task. I need to identify customers that have placed orders within the past 2 years. However, I need a subset of those records.

  1. There needs to be 1 or more orders placed between 12-24 months ago.
  2. A gap where NO orders are placed between 1-12 months ago.
  3. 1 or more new orders have been placed within the past month.

Sounds easy enough, but I’ve spent way too much time isolating the constraints without receiving the desired output.

Here’s my current code attempt:

SAMPLE DATA: (I don’t see a way to add a table, so here goes…)

Ideally, the result set from my current code should display:

I’m not married to my code as it is. I’m hoping someone can lead me to a better way to approach this task.

Thanks!

-dougbert

Advertisement

Answer

I think this will give you what you want. Your question says you want the list of customers, but your output data suggests you want a list of orders from those customers.

The key here is that your subqueries need to correlate customer_id back to the outermost A_ATEST table. The way you had it written basically meant “and there exists an order from any customer between 1 and 12 months ago”.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement