1

I built following Select query to get below results

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

Results

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

I want it to display like this:

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

so that it fills empty coupons from not empty coupon field where order id matches.

Your help will be greatly appreciated. Thanks.

4

3 回答 3

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 摆弄你的数据

于 2013-07-09T11:13:28.663 回答
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 BYand来确保每个值MAX只有一行,即使已经设置了多行。od2OrderIDOrderDetailsCoupon

于 2013-07-09T13:08:00.767 回答
0

假设 Coupon 对于每个 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
于 2013-07-09T10:39:11.383 回答