0
我對SQL仍然非常陌生,最近幾天在這些特定子查詢中遇到了問題。在SQL中有子查詢和派生表的問題
這一個應該返回3列,只返回來自「CA」供應商的記錄,並使用派生表。
-- Query 6
SELECT VendorID, VendorName, Vendors.VendorState
FROM Vendors
JOIN (SELECT VendorState
FROM Vendors) AS SubVendors ON Vendors.VendorID = SubVendors.VendorID
WHERE Vendors.VendorState = 'CA'
ORDER BY VendorID;
但是當我運行它,我得到這個錯誤:
Msg 207, Level 16, State 1, Line 6
Invalid column name 'VendorID'.
這一個返回4列,也使用派生表,子查詢的「FROM子句中的編碼。
-- Query 7
SELECT
InvoicesMain.VendorID,
MAX(InvoiceTotal) AS MaxInvoice,
MIN(InvoiceTotal) AS MinInvoice,
AVG(InvoiceTotal) AS AvgInvoice
FROM
Invoices AS InvoiceMain
JOIN
(SELECT TOP 10
VendorID, AVG(InvoiceTotal) AS AvgInvoice
FROM Invoices
GROUP BY VendorID
ORDER BY AvgInvoice DESC) AS TopVendor ON InvoicesMain.VendorID = TopVendor.VendorID)
GROUP
InvoicesMain.VendorID
ORDER BY
MaxInvoice DESC;
但我得到這個錯誤:
Msg 102, Level 15, State 1, Line 9
Incorrect syntax near ')'.
最後,我真的不知道如何做到這一點的一個;它應該重新作爲子查詢:
SELECT
InvoiceNumber, InvoiceDate, InvoiceLineItemAmount
FROM
Invoices
JOIN
InvoiceLineItems ON Invoices.InvoiceID = Invoicelineitems.InvoiceID
WHERE
VendorID = 122
ORDER BY
InvoiceDate;
請提供任何提示?
你的第一個查詢不選擇在SubVendors查詢供應商ID恢復此爲子查詢,但你正試圖加入它。您的第二個查詢在需要刪除的連接後有一個額外的支架。第三個問題是什麼?作爲一個子查詢,您只需要按語句刪除該命令,如果需要排序,則在子查詢之外執行。 – ZLK