我有两个表,即“客户”和“交易”。从当月1日开始提供优惠。
客户表
Customer_ID Email Created_Date
1 [email protected] 2015-08-14 12:25:55
2 [email protected] 2016-01-23 18:16:34
.
.
n [email protected] 2016-05-05 23:25:43
交易表
Trans_ID Customer_ID Trans_Date Amount
asd654qwe 2 2015-09-25 13:15:56 1200
dfg123xcv 56 2016-03-22 21:26:52 100
.
.
rty321cvb 4125 2016-05-05 08:42:06 500
我只需要选择当月1日之后所有客户的前3笔交易,然后,如果该客户是新客户,则他的第一笔交易有资格获得100%的现金返还。新客户的第二笔和第三笔交易有资格获得50%的现金返还。如果客户老了,那么他在本月1日之后进行的第一笔交易和第二笔交易均可分别获得50%的现金返还。
我需要每天为昨天完成的交易生成报告,并将其共享给客户团队。SQL不是我的主要任务,由于短缺,我需要对其进行研究。我正在使用excel手动完成所有这些操作。这是非常耗时的。任何人都可以让我知道可以提供预期结果的查询吗?
预期结果
c.Email c.Created_Date t.Trans_ID t.Trans_Date t.Amount Offer_Type
record record record record record First
record record record record record Repeate
record record record record record Repeate
这是您要找的东西吗?
SET @limit3 := 0, @cust := '';
--outer query determines offer type and limits the offer to three transactions per customer
SELECT Email, Created_Date, Trans_ID, Trans_Date, Amount
CASE WHEN Created_Date > First_Day THEN 'First'
ELSE 'Repeate'
END CASE AS Offer_Type,
@limit3 := if (@cust = Customer_ID, @limit3 + 1, 1) AS rowcount,
@cust := Customer_ID
--Inner query selects applicable fields, creates First_Day field,
--filters it to transactions done yesterday
FROM
(
SELECT c.Email, c.Created_Date, t.Trans_ID, t.Trans_Date, t.Amount, c.Customer_ID
DATE_ADD(LAST_DAY(c.Created_Date), interval 1 DAY), interval -1 MONTH) as First_Day
FROM Customers c
JOIN Transactions t
ON c.Customer_ID = t.Customer_ID
WHERE DATE(Trans_Date) = SUBDATE(NOW(), 1)
) AS sub
GROUP BY c.Customer_ID
HAVING rowcount <= 3
ORDER BY c.Created_Date
有点费解地在mysql中做
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句