我想在两个表上进行条件连接,并希望在第二个表中以最高状态加入。状态值为Assigned,Booked,Delivery和Closed。
SELECT
CPC.CpcID, StatusFlow = CPC.Status, Orders.CarModel, EnquiryLog.EnquiryStatus
FROM
CPC
INNER JOIN
Orders ON CPC.CpcID = Orders.CpcID
INNER JOIN
EnquiryLog ON CPC.CpcID = EnquiryLog.CpcID
WHERE
CPC.CpcID = '24092015/12'
因此,在这种情况下,它应该只显示一行EnquiryStatus' Delivery'但根据我的查询结果是:
SQL查询输出:
答案 0 :(得分:0)
如果我以正确的方式得到它:
SELECT CPC.CpcID, StatusFlow = CPC.Status, Orders.CarModel, ca.EnquiryStatus
FROM CPC
INNER JOIN Orders ON CPC.CpcID = Orders.CpcID
CROSS APPLY(SELECT TOP 1 * FROM EnquiryLog WHERE CPC.CpcID = EnquiryLog.CpcID
ORDER BY CASE EnquiryStatus
WHEN 'CLOSED' THEN 1
WHEN 'DELIVERY' THEN 2
WHEN 'BOOKED' THEN 3
WHEN 'ASSIGNED' THEN 4 END) ca
WHERE CPC.CpcID='24092015/12'