Kostas C.
Kostas C.

Reputation: 103

SQL Count valid Transactions per User

I need to get a list of customers that made a specific amount of valid transactions between two dates.

SELECT
  customer.customer_id,
  COUNT(
    CASE WHEN transaction.transaction_date>="2010-01-01" 
      THEN 1 
    ELSE NULL 
    END
  ) AS Total
FROM customer
LEFT JOIN transaction ON customer.customer_id = transaction.customer_id
GROUP BY customer.customer_id
HAVING (Total>=min_transactions AND Total<=max_transactions)

This doesn't return anything. By removing the CASE in the COUNT(..), it returns the amount of transactions per user, but it also contains invalid and out of range transactions.

Isn't the CASE loop supposed to work like that in the COUNT?

Is it a better idea to count only the transactions, without merging the two tables?

(Using MySQL)

Upvotes: 1

Views: 2483

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1271141

I think this is the query that you want:

SELECT c.customer_id, COUNT(t.customer_id) as Total
FROM customer c LEFT JOIN
     transaction t
     ON c.customer_id = t.customer_id AND
        t.transaction_date >= '2010-01-01'
GROUP BY c.customer_id
HAVING Total >= min_transactions AND Total <= max_transactions;

Notes:

  • Conditions on the second table in a LEFT JOIN usually belong in the ON clause.
  • Use single quotes for date and string constants. Double quotes can be used to escape identifiers.
  • The count() is counting from the second table. If there are no matches, the count will be 0.
  • A LEFT JOIN is needed only if min_transactions is ever 0.

Upvotes: 1

Related Questions