[英]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.
通过删除COUNT(..)中的CASE,它返回每个用户的交易量,但是它还包含无效和超出范围的交易。
Isn't the CASE loop supposed to work like that in the COUNT? CASE循环不是应该在COUNT中那样工作吗?
Is it a better idea to count only the transactions, without merging the two tables? 仅统计交易而不合并两个表是更好的主意吗?
(Using MySQL) (使用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: 笔记:
LEFT JOIN
usually belong in the ON
clause. LEFT JOIN
第二个表上的条件通常属于ON
子句。 count()
is counting from the second table. count()
从第二个表开始计数。 If there are no matches, the count will be 0
. 0
。 LEFT JOIN
is needed only if min_transactions
is ever 0
. min_transactions
为0
时才需要LEFT JOIN
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.