您好我正在尝试对2017年进行同期分析。我有以下两个表
FirstPurchases - 我确定客户首次购买的次数大于1.原因是我们在首次交易时购买的信用卡验证少于1 usd。
交易 - 这是记录客户所有购买和退款交易的表格。
我写的sql是以下
DROP TABLE IF EXISTS `FirstPurchases`;
CREATE TABLE `FirstPurchases`
(
SELECT account_id,MIN(created_date) AS transaction_date
FROM `transaction`
WHERE transaction.amount > 1
GROUP BY account_id
);
DELETE FROM `FirstPurchases`
WHERE YEAR(transaction_date) = 2016;
SELECT u.MonthOffset AS MONTH,
SUM(s.MonthOffset = 0) AS d0,
SUM(s.MonthOffset = 1) AS d1,
SUM(s.MonthOffset = 2) AS d2,
SUM(s.MonthOffset = 3) AS d3,
SUM(s.MonthOffset = 4) AS d4,
SUM(s.MonthOffset = 5) AS d5,
SUM(s.MonthOffset = 6) AS d6,
SUM(s.MonthOffset = 7) AS d7,
SUM(s.MonthOffset = 8) AS d8,
SUM(s.MonthOffset = 9) AS d9,
SUM(s.MonthOffset = 10) AS d10,
SUM(s.MonthOffset = 11) AS d11,
SUM(s.MonthOffset = 12) AS d12
FROM (
SELECT
account_id,
MONTH(transaction_date) AS MonthOffset
FROM `FirstPurchases`
WHERE transaction_date >= CURDATE() - DATEDIFF(CURDATE(),'2017-01-01')
) AS u
LEFT JOIN (
SELECT DISTINCT
transaction.account_id,
PERIOD_DIFF(DATE_FORMAT(transaction.created_date,'%Y%m'),DATE_FORMAT(FirstPurchases.transaction_date,'%Y%m')) AS MonthOffset
FROM `transaction`
LEFT JOIN `FirstPurchases` ON (transaction.account_id = `FirstPurchases`.account_id)
WHERE `transaction`.created_date >= CURDATE() - DATEDIFF(CURDATE(),'2017-01-01')
) AS s
ON s.account_id = u.account_id
GROUP BY u.MonthOffset;
虽然我确信d0是正确的。剩下的数字让我觉得虚荣。我手动完成了这个练习,数字不匹配。任何人都可以投下眼睛,看看我哪里出错了?任何帮助都感激不尽。
答案 0 :(得分:0)
事实证明我有点笨拙,查询是正确的。我忘了在左连接中过滤掉退款。因此,如果有人想将此作为队列分析的模板,那么你去:)