我有一些SQL语句的问题。我需要在以下设置中为每个DeliveryDate
找到下一个Customer
。
表格
Customer (id)
DeliveryOrder (id, deliveryDate)
DeliveryOrderCustomer (customerId, deliveryOrderId)
每个Customer
可能在同一DeliveryOrders
上有多个deliveryDate
。我只是弄清楚如何只为每个客户获得一个deliveryDate
。该日期应该是今天之后的下一个DeliveryDate
。我觉得我需要某种“为每个人”,但我不知道如何在SQL中解决它。
答案 0 :(得分:1)
这将使用subselect给出预期结果。考虑到 current_date 可能是特定于rdbms的,它适用于Oracle。
select c.id, o.date
from customer c
inner join deliveryordercustomer co o on co.customerId = c.id
inner join deliveryorder o on co.deliveryOrderId = o.id
where o.date =
(select min(o2.date)
from deliveryorder o2
where o2.id = co.deliveryOrderId and o2.date > current_date)
答案 1 :(得分:1)
你需要使用一个分组。有很多方法可以做到这一点,这是我的解决方案,在同一天为客户考虑多个订单,并允许您查询不同的交付时段,第一,第二等。这假设Sql Server 2005及更高版本。
;with CustomerDeliveries as
(
Select c.id, do.deliveryDate, Rank()
over (Partition BY c.id order by do.deliveryDate) as DeliverySlot
From Customer c
inner join DeliveryOrderCustomer doc on c.id = doc.customerId
inner join DeliveryOrder do on do.id = doc.deliveryOrderId
Where do.deliveryDate>GETDATE()
Group By c.id, do.deliveryDate
)
Select id, deliveryDate
From CustomerDeliveries
Where DeliverySlot = 1
答案 2 :(得分:1)
另一个更简单的版本
select c.id, min(o.date)
from customer c
inner join deliveryordercustomer co o on co.customerId = c.id
inner join deliveryorder o on co.deliveryOrderId = o.id and o.date>getdate()
group by c.id