使用相关子查询更新查询

时间:2013-01-12 16:07:23

标签: sql-server-2008 tsql

我正在尝试将Foxpro应用程序转换为.NET。作为转换的一部分,我将数据从DBF表转换为Sql server。

我需要根据Orders表,FirstOrder和LastOrder在Customer表中提出几个新字段。

我似乎无法在TSql中如何做到这一点。我知道我在Foxpro中是如何做到的,如果必须的话,我实际上仍然可以在那里做,但我知道我需要在Sql中学习如何做到这一点。

这是基本结构。 Customer Table有一个Id,然后是我需要更新的FirstOrder和LastOrder字段。 订单表有OrderDate,但这是真正的曲线。客户ID可以存在于Order:ShipperId,PickupId,ConsigneeId,DeliveryId或BillingId中的5个不同字段中。

类似于:

UPDATE customers
SET FirstOrderDate = 
(Select MIN(OrderDate)
FROM Orders o
WHERE o.ShipperId = Customers.Id or
o.PickupId = Customers.Id or
o.ConsigneeId = Customers.Id or
o.DeliveryId = Customers.Id or
o.BillingId = Customers.Id)

似乎无法找到如何将子查询与主更新查询联系起来。

谢谢, -sid


编辑: 这是基于MarkD建议的SELECT工作:

Select C.Id,Min(o.OrderDate) as firstorder, MAX(o.OrderDate) as lastorder
from Customers C
JOIN Orders o
on o.ShipperId = C.Id or
        o.PickupId = C.Id or
        o.ConsigneeId = C.Id or
        o.DeliveryId = C.Id or
        o.BillingId = C.Id 
GROUP BY C.Id

现在我将它作为子查询或游标用于回发到Customers表吗?

2 个答案:

答案 0 :(得分:2)

虽然我认为JOIN标准极不可能,但看起来你正试图这样做?

编辑:我已经修改了JOIN条件,但这就是您所追求的目标。 Grouping By'列的OR列是奇数。

;WITH MinOrderDates AS
(
    SELECT   CustID 
            ,OrderDate  = MIN(OrderDate)
    FROM Orders
    GROUP BY CustID
)

UPDATE C
SET FirstOrderDate = MIN(O.OrderDate)
FROM Customers      C
JOIN MinOrderDates  O   ON C.Id = O.CustID

这是您使用OR s

查询的结果
;WITH MinOrderDates AS
(
    SELECT   ShipperId
            ,PickupId
            ,ConsigneeId
            ,DeliveryId
            .BillingId
            ,OrderDate  = MIN(OrderDate)
    FROM Orders
    GROUP BY ShipperId
            ,PickupId
            ,ConsigneeId
            ,DeliveryId
            .BillingId
)

UPDATE C
SET FirstOrderDate = MIN(O.OrderDate)
FROM Customers      C
JOIN MinOrderDates  O   ON o.ShipperId     = C.Id or
                           o.PickupId      = C.Id or
                           o.ConsigneeId   = C.Id or
                           o.DeliveryId    = C.Id or
                           o.BillingId     = C.Id 

编辑:虽然我很难找到你发布的语法错误。

答案 1 :(得分:0)

试试这个

UPDATE customers
SET FirstOrderDate = 
(Select MIN(OrderDate)
FROM Orders
WHERE ShipperId = Customers.Id or
PickupId = Customers.Id or
ConsigneeId = Customers.Id or
DeliveryId = Customers.Id or
BillingId = Customers.Id)