[英]Count the number of repeating pairs of information
I have a table with customer_ID, date, and payment_method as 3 columns.我有一张表,其中 customer_ID、date 和 payment_method 为 3 列。 payment_method can be 'cash', 'credit', or 'others'. payment_method 可以是“现金”、“信用”或“其他”。 I want to find out the number of customers who have used credit as a payment method more than 5 times, in the last 6 months.我想了解在过去 6 个月内使用信用卡作为付款方式超过 5 次的客户数量。
I found this solution for displaying the rows where the customer used credit:我找到了这个解决方案来显示客户使用信用的行:
SELECT customer_ID, payment_method, COUNT(*) AS unique_pair_repeats
FROM tab1
WHERE customer_ID IS NOT NULL
GROUP BY customer_ID, payment_method
HAVING count(*) > 1;
The problem is, I don't want a list of the names/ids, I want to know how many people used their credit card for a purchase 5 times or more in the last 6 months.问题是,我不想要名称/ID 的列表,我想知道有多少人在过去 6 个月内使用信用卡购买了 5 次或更多。
This is one way you could do it:这是您可以做到的一种方法:
SELECT COUNT(*)
FROM
(
SELECT customer_id
FROM tab1
WHERE
customer_ID IS NOT NULL and
payment_method = 'credit' and
tran_date > add_months(sysdate, -6)
GROUP BY customer_ID
HAVING count(*) > 5
) x
The inner query generates a list of all customer ids that have used credit more than 5 times in 6 months.内部查询生成在 6 个月内使用信用超过 5 次的所有客户 ID 的列表。 The outer query counts them外部查询对它们进行计数
You might feel it more logical to write it like this:你可能觉得这样写更合乎逻辑:
SELECT COUNT(*)
FROM
(
SELECT customer_id, count(*) as ctr
FROM tab1
WHERE
customer_ID IS NOT NULL and
payment_method = 'credit' and
tran_date > add_months(sysdate, -6)
GROUP BY customer_ID
) x
WHERE x.ctr > 5
So, remove customer_ID, payment_method,
from select
.因此,从select
中删除customer_ID, payment_method,
。
Though, that still doesn't answer "at least 5 times in last 6 months", so you need another condition: date
(presuming you use Oracle, although you didn't tag the question but - you do use Oracle SQL Developer):虽然,这仍然不能回答“过去 6 个月中至少 5 次”,所以你需要另一个条件: date
(假设你使用 Oracle,虽然你没有标记问题,但是 - 你确实使用 Oracle Z970CACA840A0641CB07 开发人员):
and date_column >= add_months(trunc(sysdate), -6)
Finally, something like this might help:最后,这样的事情可能会有所帮助:
SELECT COUNT(*) AS unique_pair_repeats --> changes here
FROM tab1
WHERE customer_ID IS NOT NULL
and date_column >= add_months(trunc(sysdate), -6) --> here
GROUP BY customer_ID, payment_method
HAVING count(*) >= 5; --> here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.