-1

我有一个客户列表和订单日期,我想找到在 30 天内至少下过两次订单的客户。

例如,如果客户 12 于 2013 年 6 月 20 日订购了一种产品,并于 2013 年 1 月 7 日再次订购。我希望查询带回客户 12

谢谢

4

3 回答 3

1

像这样的东西应该可以使用自联接来满足您的需求。您可能想要索引客户标识符是什么(在这种情况下customer_name

SELECT DISTINCT o1.customer_name
FROM orders o1
JOIN orders o2
  ON o1.customer_name = o2.customer_name
 AND o1.id <> o2.id 
 AND ABS(DATEDIFF(day, o1.order_date, o2.order_date)) < 30

一个用于测试的 SQLfiddle

如果您运行的是 SQL Server 2012,这可能(应该)提供更好的性能;

WITH cte AS (
  SELECT customer_name, order_date od1,
       LAG(order_date) OVER (PARTITION BY customer_name ORDER BY order_date) od2
  FROM orders
)
SELECT DISTINCT customer_name 
FROM cte
WHERE DATEDIFF(day, od2, od1) < 30

另一个 SQLfiddle

于 2013-07-24T12:08:54.253 回答
0
SELECT 
    customerid,
    count(*) 
FROM
    orderTable 
WHERE 
    orderDate between <startDate> and <endDate>
GROUP BY 
    customerid 
HAVING 
     count(*) >= 2
于 2013-07-24T12:00:08.920 回答
0
SELECT 
    customer_name, 
    COUNT(
        CASE WHEN datediff( dd, order_date, getdate() ) 
            <=30 THEN 1 
        END
    ) AS order_count   
FROM 
    order_table 
GROUP BY 
    customer_name 
于 2013-07-24T12:29:22.740 回答