我试图找出在过去七天内没有下订单的客户。基本上,我有3个表:客户,订单和help_desk_agents。
我正在尝试找出获取此信息的最佳方法。
SQL波纹管检索客户信息,服务台代理111和每个客户的订单的最后日期:
SELECT DISTINCT customers.customer_id,
customers.customer_name,
agents.help_desk_agent,
Max(orders.order_date)
FROM customers
LEFT JOIN (SELECT DISTINCT customers.customer_id,
orders.order_date
FROM orders
GROUP BY 1,
2) orders2
ON customers.customer_id = orders2.customer_id
LEFT JOIN help_desk_agents
ON customers.help_desk_agent_id =
help_desk_agents.help_desk_agent_id
WHERE customer.help_desk_agent_id = 111
GROUP BY 1,
2,
3
我想以某种方式过滤过去7天未下订单的客户。
答案 0 :(得分:2)
尝试在查询的和处添加此内容:
having max(orders.order_date) < dateadd(day, -7, getdate())
答案 1 :(得分:0)
您可以尝试
Datediff(dd,<datecolumn>,getdate())
并使用
>= 7
作为条件。
答案 2 :(得分:0)
您想要的查询应如下所示:
SELECT c.customer_id, c.customer_name, a.help_desk_agent,
Max(orders.order_date)
FROM customers c JOIN
(SELECT o.customer_id, MAX(o.order_date) as max_order_date
FROM orders o
GROUP BY o.customer_id
) o
ON c.customer_id = o.customer_id
WHERE c.help_desk_agent_id = 111 AND
o.max_order_date < dateadd(day, -7, getdate());
您的查询有多个问题:
customers.customer_id
。select distinct
是不必要的。LEFT JOIN
是不必要的,因为假定客户至少有一个订单,并且您需要与代理商表匹配。customer
表中。