I'm attempting to write a query to pull credit cards that were used at at least two merchants from a list of merchants.
My table has card_number and merchant_name fields. There is row for every card transaction.
Lets say I have merchant_a, merchant_b, merchant_c, and merchant_d. I want to find cards that were used at least two of those merchants. I'm not sure how I would go about finding cards that were used at at least two of those merchants and not end up with cards that were used at say merchant_a twice.
Any help would be greatly appreciated. Hopefully I explained it well enough. If not, I'll be happy to try and clarify.
I need to the merchant name to be one that exists in a list of merchant names though. My table contains tens of thousands of merchant names. I need to look at cards used at at least two merchants from a small list of merchants.
One more question. In the same table it also has the date of the transaction. What if I wanted to only see those cards where the transactions that took place at two of those merchants are no more than 3 days apart?
SELECT
cardNumber
FROM
Tbl t1
WHERE
mecrchant_name IN ( 'one', 'two', 'three', 'last' )
AND EXISTS
(
SELECT *
FROM Tbl t2
WHERE
t2.mecrchant_name <> t1.mecrchant_name
AND t2.mecrchant_name IN ( 'one', 'two', 'three', 'last' )
AND ABS(DATEDIFF(dd,t1.transactionDate,t2.transactionDate)) <= 3
)
GROUP BY
cardNumber
HAVING
COUNT(DISTINCT mecrchant_name) > 1;