我有一个简单的Customers
(customerID)表和一个Orders
表(orderID,orderdate)
我需要获得两周前收到订单的所有客户的清单,以及他们在该周之前所有订单的数量。
SELECT c.id_customer
FROM customer AS c
JOIN order AS o ON o.customerID = c.customerID
WHERE o.delivery_date = DATEADD(Day,-14,GETDATE())
但我不知道如何在那个周之前获得订单数量。
答案 0 :(得分:1)
您可以使用<=
获取行并使用having
子句检查在给定日期是否确实存在一行:
select c.id_customer, count(*) as order_count
from customer as c
join orders as o on o.customerID = c.customerID
where o.delivery_date <= DATEADD(Day, - 14, GETDATE())
group by c.id_customer
having count(case when o.delivery_date = DATEADD(Day, -14, GETDATE()) then 1 end) > 0;
另请注意,我将表名order
更改为orders
,因为order
是SQL保留关键字,使用关键字作为表/列标识符通常是个坏主意。
答案 1 :(得分:0)
SELECT c.customerID,o.orderID, count(o.delivery_date)
FROM customer AS c
JOIN order AS o ON o.customerID = c.customerID
WHERE o.delivery_date = DATEADD(Day,-14,GETDATE())
group by c.customerID,o.orderID
答案 2 :(得分:0)
尝试使用其他样本数据
Declare @DaysAgo int=14 --para to be pass in proc
declare @To Datetime=DATEADD(second,-1,cast((DATEADD(Day, - (@DaysAgo-1), cast(GETDATE() as date)) ) as DATETIME))
declare @From Datetime=cast((DATEADD(Day, - @DaysAgo, cast(GETDATE() as date)) ) as DATETIME)
select c.id_customer, count(*) as order_count
from customer as c
join orders as o on o.customerID = c.customerID
where o.delivery_date >= @From AND
o.delivery_date <= @To
group by c.id_customer