我正在尝试加入表变量表和另一个表。
@ProcessTbl OrderDetail
Order ID
Status Order
Approved DateTime
Domain Status
OrderDetail表有多列用于相同的订单。例如
ID Order DateTime Status
1 1 11-17-10 Recived
2 1 11-18-10 Processing
3 1 11-19-10 shipped
所以我想要联接做的是从@processtbl获取订单号(表变量) 并且对于max(id),在这种情况下获取日期时间最大id为3
所以我的结果应该是
order status approved domain datetime
1 shipped true finance 11-19-10
SELECT t.order
,[od.DateTime]
,t.Status
,t.Domain
,t.Approved
FROM @ProcessTable t
JOIN OrderDetail od ON od.order= t.order
WHERE od.ID = (SELECT MAX(id) FROM orderdetail WHERE od.order = t.order )
ORDER BY od.[DateTime], Approved ASC
但是我仍然会获得重复的记录,看起来它正在对两个表进行评分。 我怎样才能获得不同的记录?
答案 0 :(得分:4)
select p.order, od.status, p.approved, p.domain, od.datetime
from @ProcessTable p
inner join (
select Order, max(ID) as MaxID
from OrderDetail
group by Order
) odm
inner join OrderDetail od on odm.Order = od.Order
and odm.MaxID = od.ID
答案 1 :(得分:1)
想一想,你试过SELECT DISTINCT
吗?
答案 2 :(得分:0)
WHERE od.ID = (SELECT MAX(id) FROM orderdetail WHERE od.order = t.order )
od.order不引用子查询中的orderdetail表,而是引用外部的实例。
尝试类似:WHERE od.ID = (SELECT MAX(id) FROM orderdetail as od1 WHERE od1.order = t.order )