【发布时间】:2017-07-15 03:29:16
【问题描述】:
我正在尝试查找一个查询,该查询将为我提供在同一个月内与 2 个不同实体进行交易的客户数量。也就是说,同月内与company_a 和company_b 交易的customer_ids。这是我目前所拥有的:
SELECT Extract(year FROM company_a_customers.transaction_date)
|| Extract(month FROM company_a_customers.transaction_date) AS
payment_month,
Count(UNIQUE(company_a_customers.customer_id))
FROM (SELECT *
FROM my_table
WHERE ( merchant_name LIKE '%company_a%' )) AS company_a_customers
INNER JOIN (SELECT *
FROM my_table
WHERE ( merchant_name = 'company_b' )) AS
company_b_customers
ON company_a_customers.customer_id =
company_b_customers.customer_id
GROUP BY Extract(year FROM company_a_customers.transaction_date)
|| Extract(month FROM company_a_customers.transaction_date)
问题在于,这给了我按月与公司 A 进行交易的所有客户的总和,这些客户也曾经与公司 B 进行过交易。
如果我把它缩减到一个特定的月份,它显然会给我正确的重叠,因为查询只获取那个月的 ID:
SELECT Extract(year FROM company_a_customers.transaction_date)
|| Extract(month FROM company_a_customers.transaction_date) AS
payment_month,
Count(UNIQUE(company_a_customers.customer_id))
FROM (SELECT *
FROM my_table
WHERE ( merchant_name LIKE '%company_a%' )
AND transaction_date >= '2017-06-01'
AND transaction_date <= '2017-06-30') AS company_a_customers
INNER JOIN (SELECT *
FROM my_table
WHERE ( merchant_name = 'company_b' )
AND transaction_date >= '2017-06-01'
AND transaction_date <= '2017-06-30') AS
company_b_customers
ON company_a_customers.customer_id =
company_b_customers.customer_id
GROUP BY Extract(year FROM company_a_customers.transaction_date)
|| Extract(month FROM company_a_customers.transaction_date)
如何在一个查询中执行此操作,以获取在给定月份内与两家公司进行交易的客户的月度总计?
期望的结果:第二个查询的输出,但每个月都在数据库中。换句话说:
2017 年 1 月:xx,xxx 个重叠客户 2017 年 2 月:xx,xxx 重叠客户 2017 年 3 月:xx,xxx 重叠客户
非常感谢。
【问题讨论】:
-
编辑您的问题。 (1) 使用您正在使用的数据库进行标记。 (2) 提供样本数据。 (3) 提供期望的结果。
-
我已经进行了建议的修改