2014-07-22 153 views
0

我試圖從數據表中獲取最新價格。該數據會出來像這樣:SQL左連接子查詢問題

Part Price Date

----- ----- --------

10525 .25 1/1/2010

10525 5.00 7/6/2014

10526 4.25 7/1/2014

我試圖用加盟,使我能得到的「10525 5.00 2014年7月6日」的結果,但它給我這個錯誤:

The column prefix 'orderdtl' does not match with a table name or alias name used in teh query. Statement(s) could not be prepared."

如果我把這個連接拿出來,它工作得很好。我哪裏錯了?

SELECT orderdtl.partnum, orderdtl.docunitprice, orderhed.orderdate 
FROM mfgsys80.dbo.orderdtl AS orderdtl, mfgsys80.dbo.orderhed AS orderhed 
INNER JOIN(
    SELECT orderdtl.partnum, MAX(orderhed.orderdate) AS 'maxDate' 
    FROM mfgsys80.dbo.orderdtl AS orderdtl, mfgsys80.dbo.orderhed AS orderhed 
    GROUP BY orderdtl.partnum 
) AS Temp 
    ON orderdtl.partnum = Temp.partnum AND orderhed.orderdate = Temp.maxDate 
WHERE orderdtl.ordernum = orderhed.ordernum AND ((orderdtl.custnum=74)) 
ORDER BY orderdtl.partnum 

回答

0

您查詢的形式是錯誤的。它應該像

SELECT orderdtl.partnum, orderdtl.docunitprice, orderhed.orderdate 
FROM mfgsys80.dbo.orderdtl AS orderdtl 
JOIN mfgsys80.dbo.orderhed AS orderhed 
ON orderdtl.ordernum = orderhed.ordernum 
INNER JOIN(
    SELECT ol.partnum, MAX(od.orderdate) AS 'maxDate' 
    FROM mfgsys80.dbo.orderdtl ol 
    JOIN mfgsys80.dbo.orderhed od 
    ON ol.ordernum = od.ordernum 
    GROUP BY ol.partnum 
) Temp 
ON orderdtl.partnum = Temp.partnum 
AND orderhed.orderdate = Temp.maxDate 
WHERE orderdtl.custnum=74 
ORDER BY orderdtl.partnum 
+0

感謝您的幫助!我的SQL非常生疏,但現在我看到它的意義是有道理的。 – Error