0
Orders
OrderNo    OrderItems   CusID
5001       2            300001
5002       1            300001
5003       2            300002

OrderDetails
OrderDetailsNo     OrderNo   OrderItem
70001              5001      Hotdog
70002              5001      Pancake
70003              5002      Iced Tea
70004              5003      Bacon Sandwich
70005              5003      Ham

select top 1 from Orders Order By OrderNo Desc如果没有连接,我用来获取最后一行。

OrderNo    OrderItems   CusID
5003       2            300002

如何获得带有左外连接的订单的最后结果?

结果

OrderNo    OrderItems   CusID     OrderDetailsNo  OrderItem
5003       2            300002    70004           Bacon Sandwich
5003       2            300002    70005           Ham

示例外连接

select  Orders.OrderNo, OrderItems, CusID, OrderDetailsNo, OrderItem 
From Orders
left outer join
OrderDetails
on Orders.OrderNo = OrderDetails.OrderNo
4

2 回答 2

1

这应该有效:

select  Orders.OrderNo, OrderItems, CusID, OrderDetailsNo, OrderItem 
From (select top 1 * from Orders Order By OrderNo Desc) Orders
left outer join
OrderDetails
on Orders.OrderNo = OrderDetails.OrderNo

或者

select top 1 with ties Orders.OrderNo, OrderItems, CusID, OrderDetailsNo, OrderItem 
From Orders
left outer join
OrderDetails
on Orders.OrderNo = OrderDetails.OrderNo
Order By Orders.OrderNo Desc
于 2013-09-16T09:16:20.207 回答
0
; WITH cte AS (
  SELECT TOP (1)
         orderno
       , orderitems
       , CusID
  FROM   orders
  ORDER
      BY orderno DESC
)
SELECT cte.orderno
     , cte.orderitems
     , cte.CusID
     , orderdetails.orderdetailsno
     , orderdetails.orderitem
FROM   cte
 LEFT
  JOIN orderdetails
    ON cte.orderno = orderdetails.orderno
于 2013-09-16T09:16:45.360 回答