我有两张桌子。我需要提取第一个表中的所有列。然后我必须从第一个表中选择与max of id
匹配的orderid
。以下是我的情景:
First table Second table
id Orderid Name Orderid Status
1 3 4 3 4
2 4 xx 3 5
3 4
输出应为
id Orderid Name Status
1 3 4 4
2 4 xx -
答案 0 :(得分:0)
假设第二个表有一个日期时间(或某物),可用于确定哪一行最近更新...
Select f.id, f.OrderId, f.Name, s.Status
From firstTable f
left join secondTable s
on s.OrderId = f.OrderId
and s.Updated =
(Select max(updated)
from secondTable
where orderId = s.OrderId)
仅当s中只有一行具有相同的updated
值时才会起作用。更好的是在s中使用主键值(如果存在...)
答案 1 :(得分:0)
使用OUTER APPLY
:
select ft.*, oa.Status
from ft
outer apply(select top 1 Status
from st
where ft.Orderid = st.Orderid
order by st.id desc) oa --here you should order by appropriate column to determine which is last row
答案 2 :(得分:0)
检查这是否完成了工作
SELECT ft.id
,ft.OrderID
,ft.NAME
,min(sst.STATUS)
FROM ft
LEFT JOIN (
SELECT TOP 1 st.orderid
,st2.STATUS
FROM st
INNER JOIN st AS st2 ON st.id = st2.id
ORDER BY st.orderid DESC
) sst ON ft.OrderID = sst.orderid
GROUP BY ft.id
,ft.OrderID
,ft.NAME;
我使用了来自Giorgi Nakeuri的SQLfiddle来表格结构......我希望他不介意......我不知道SQLFiddle的方式...很棒的网站