查找在30天内下订单的客户

时间:2013-07-24 11:57:13

标签: sql-server

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

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

由于

3 个答案:

答案 0 :(得分: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

An SQLfiddle to test with

如果您正在运行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

Another SQLfiddle

答案 1 :(得分:0)

SELECT 
    customerid,
    count(*) 
FROM
    orderTable 
WHERE 
    orderDate between <startDate> and <endDate>
GROUP BY 
    customerid 
HAVING 
     count(*) >= 2

答案 2 :(得分: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