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
如何通过左外连接获得Order的最后结果?
结果
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
答案 0 :(得分: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
答案 1 :(得分: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