【问题标题】:SQL select first 3 records from given dateSQL从给定日期选择前3条记录
【发布时间】:2016-05-06 15:19:30
【问题描述】:

我有两张表,即客户和交易。有从当月 1 日开始的优惠。

  1. 新客户(本月 1 日之后创建)的首次交易将获得 100% 的现金返还。
  2. 老客户(本月 1 日之前创建)自本月 1 日以来的第一笔和第二笔交易可获得 50%。
  3. 第 1 点优惠的客户也有资格获得第 2 点优惠。

客户表

Customer_ID   Email       Created_Date
1             abc@g.com   2015-08-14 12:25:55
2             xyz@s.com   2016-01-23 18:16:34
.
.
n             ags@h.com   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

【问题讨论】:

  • 这个查询的输出是什么样的(不是最终查询):SELECT c.Customer_ID, t.Trans_ID, t.Trans_Date, t.Amount FROM customers_table c JOIN transactions_table t ON c.Customer_ID = t.Trans_ID WHERE MONTH(t.Trans_Date) = MONTH(CURDATE()) AND YEAR(t.Trans_Date) = MONTH(CURDATE()) ORDER BY t.Customer_ID, t.Trans_Date

标签: mysql sql


【解决方案1】:

这就是你要找的吗?

 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中做的有点复杂

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2013-08-01
    • 2020-12-16
    • 2011-01-24
    • 2020-08-22
    • 2011-06-16
    • 1970-01-01
    相关资源
    最近更新 更多