I have a customer transaction table with columns customer_number, transaction_date, transaction_code, transaction_amount and a few other columns.
For each customer_number in my predefined list (let's say 1,2,3,4), I want to get the earliest transactions where a code 12 transaction_code occurs after a code 3 transaction_code. So for example, if customer 1 had a transaction code 12 which occurred anytime after a transaction code 3, I would want to get both the transaction rows for customer 1 (the earliest transaction 12, and the earliest transaction 3 which occurs before it). Same for any other customers in my list that have a transaction code 12 occurring after a transaction code 3.
Here is what I have so far. I know why it doesn't work but I can't figure out how to make it get what I want. The below code checks if the transaction code 12 date is greater than the minimum of all transaction code 3 dates, not just for each particular customer_number.
SELECT t1.* from trans_table t1
WHERE t1.transaction_date >
(select min(t2.transaction_date)
from trans_table t2
WHERE t2.customer_number= t1.customer_number
AND t2.transaction_code = 3
)
AND t1.transaction_code = 12
AND t1.customer_number in (1,2,3,4)
1条答案
按热度按时间kr98yfug1#
Here's a quick and dirty solution that might work:
The idea is to use a gaps and island style of query to group the transactions together by "flag". This flag is increased every time a number combination of transactions occurs.
The details here:
It's a bit involved query, but avoids some other complicated things, so maybe it will work out for you