SQL Server:从非空列填充Null字段,以获取具有相同ID的多个行

时间:2013-07-09 10:26:45

标签: sql sql-server

我构建了以下Select查询以获得以下结果

SELECT Orders.OrderID, OrderDetails.ProductCode, OrderDetails.Coupon
From Orders, OrderDetails
WHERE Orders.OrderID=OrderDetails.OrderID

结果

Order ID    Product Code    Coupon
22          A
22          B                XYZ
22          C
23          D                123
24          E

我希望它显示如下:

Order ID    Product Code    Coupon
22          A                XYZ
22          B                XYZ
22          C                XYZ
23          D                123
24          E

这样它就会从订单ID匹配的空白优惠券字段中填充空优惠券。

非常感谢您的帮助。感谢。

3 个答案:

答案 0 :(得分:0)

假设优惠券对每个OrderID都是唯一的。

SELECT o1.OrderID, o2.Coupon
FROM OrderDetails o1 LEFT JOIN
(SELECT DISTINCT OrderID, Coupon FROM OrderDetails WHERE NOT Coupon IS NULL) AS o2 ON o1.OrderID = o2.OrderID

答案 1 :(得分:0)

SELECT
t1.OrderID,
t1.ProductCode,
MAX(ISNULL(t2.Coupon,'')) as CouponCode,
t1.CustomerName
--Here you have select list by using alias 't' 
--don't forget it to add in group by clause
FROM
(
    select  O.OrderID,OD.ProductCode,OD.CouponCode as Coupon,C.CustomerName
    --Here add the list of columns
    from Orders O
    inner join OrderDetails OD on O.OrderID=OD.OrderID
    Inner join customers C on O.CustomerID=C.CustomerID
)t1
INNER JOIN (
                select  O.OrderID
                from Orders O
                inner join OrderDetails OD on O.OrderID=OD.OrderID
                Inner join customers C on O.CustomerID=C.CustomerID
            )t2 ON
            CAST(t1.OrderID AS VARCHAR)=
            CAST(t2.OrderID AS VARCHAR)
GROUP BY t1.OrderID,
t1.ProductCode,
t1.CustomerName
--Add the extra fields.
order by t1.OrderID

<强> SQL Fiddle with Your Data

答案 2 :(得分:0)

这有点丑陋,但做的工作是:

SELECT o.OrderID, od1.ProductCode, COALESCE(od1.Coupon,od2.Coupon)
From
   Orders o
       inner join
   OrderDetails od1
       on
           o.OrderID=od1.OrderID
       left join
   (select OrderID,MAX(Coupon) as Coupon from OrderDetails
           where Coupon is not null group by OrderID) od2
       on
           o.OrderID=od2.OrderID

正在使用GROUP BYMAX来确保每个od2OrderID中只有一行,即使OrderDetails中的多行已经有Coupon设置。