简体   繁体   中英

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)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM