MySQL - 选择在过去y天内至少生成x个订单并且最近z天没有订购的客户

时间:2017-11-05 05:24:06

标签: mysql sql

我正在尝试让客户在过去x天内至少订购y个订单并且在过去z天内没有订购,所以我的客户可以知道哪些客户“离开”而不回来。

我的表非常简单:

订单

- ID
- Created (UNIX timestamp)
- CustomerID

客户

- ID
- Name
- Phone

我在过去x天内成功选择了y个订单,但我无法加入数据,所以我只会收到没有订购上一个z的客户天

这是我对在过去30天内发出超过1个订单的客户的查询:

SELECT
    COUNT(t1.CustomerID) as customer_count,
    t2.ID as customer_id,
    t2.Name,
    t2.Phone
FROM
    Orders t1
JOIN
    Customers t2
        ON t1.CustomerID = t2.ID
WHERE
    t1.Created BETWEEN (UNIX_TIMESTAMP() - (86400*30)) AND UNIX_TIMESTAMP()
GROUP BY
    t2.ID
HAVING customer_count >= 2

2 个答案:

答案 0 :(得分:1)

由于您在第一部分中取得了成功,而第二部分主要是相同的,因此您可以通过复制查询,进行微小修改并将其作为子查询添加到SELECT COUNT(ord.CustomerID) as order_number, cust.ID, cust.Name, cust.Phone FROM Customers cust LEFT OUTER JOIN Orders ord ON cust.ID = ord.CustomerID WHERE ord.Created BETWEEN (UNIX_TIMESTAMP() - (86400*30)) AND UNIX_TIMESTAMP() AND order_number >= 2条件来轻松实现。对于在过去7天内没有订购任何订单的客户,请尝试此操作:

HAVING

注意:

  • 我将条件从SELECT COUNT(o1.CustomerID) as customer_count, c1.ID as customer_id, c1.Name, c1.Phone FROM Customers c1 LEFT JOIN Orders o1 ON o1.CustomerID = c1.ID WHERE o1.Created BETWEEN (UNIX_TIMESTAMP() - (86400*30)) AND UNIX_TIMESTAMP() GROUP BY c1.ID HAVING customer_count > 1 AND (SELECT COUNT(o2.CustomerID) as customer_count, FROM Customers c2 LEFT JOIN Orders o2 ON o2.CustomerID = c2.ID WHERE o2.Created BETWEEN (UNIX_TIMESTAMP() - (86400*7)) AND UNIX_TIMESTAMP() AND c2.ID = c1.ID GROUP BY c2.ID) = 0 更改为customer_count >= 2,因为它更好。
  • 我建议从主表customer_count > 1 开始,然后加入Customers,因为感觉更自然。
  • 我还建议使用Orderst1更有意义的别名。例如,t2c读得更好。通过上述查询,您可以执行oc1c2o1等操作。

编辑由于子查询只计算一个给定客户的订单,因此我们不需要进行分组,因此我们可以像这样简化:

o2

答案 1 :(得分:0)

虽然无关紧要,但我个人觉得将连接表放在等号的右侧看起来比较整洁且容易理解 - 所以在这个例子中我会加入customers.id到{{ 1}}而不是相反。我没有运行以下但它应该有效:



orders.customerid