。
SELECT InvoiceNumber, InvoiceDate,
(SELECT InvoiceLineItemAmount
FROM InvoiceLineItems
WHERE Invoices.InvoiceID = Invoicelineitems.InvoiceID)
AS InvoiceLineItemAmount
FROM Invoices
WHERE VendorID = 122
ORDER BY InvoiceDate
如果你的子查詢返回多個值,那麼你有幾種選擇。
你可以抓住的TOP 1
SELECT InvoiceNumber, InvoiceDate,
(SELECT TOP 1 InvoiceLineItemAmount
FROM InvoiceLineItems
WHERE Invoices.InvoiceID = Invoicelineitems.InvoiceID)
AS InvoiceLineItemAmount
FROM Invoices
WHERE VendorID = 122
ORDER BY InvoiceDate
您可以使用聚合函數
SELECT InvoiceNumber, InvoiceDate,
(SELECT MAX(InvoiceLineItemAmount)
FROM InvoiceLineItems
WHERE Invoices.InvoiceID = Invoicelineitems.InvoiceID)
AS InvoiceLineItemAmount
FROM Invoices
WHERE VendorID = 122
ORDER BY InvoiceDate
,也可以使用XML
SELECT InvoiceNumber, InvoiceDate,
STUFF((
SELECT ', ' + LTRIM(InvoiceLineItemAmount)
FROM InvoiceLineItems
WHERE Invoices.InvoiceID = Invoicelineitems.InvoiceID
FOR XML PATH('')),
1, 2, '') AS InvoiceLineItemAmount
FROM Invoices
WHERE VendorID = 122
ORDER BY InvoiceDate
或者,@MartinSmith連接結果,您可以反轉該關係並掛起InvoiceLineItems。不知道你的模式約束,你可能遇到同樣的returns more than one value
問題。
SELECT (SELECT InvoiceNumber
FROM InvoiceLineItems
WHERE Invoices.InvoiceID = Invoicelineitems.InvoiceID)
AS InvoiceNumber,
(SELECT InvoiceDate
FROM InvoiceLineItems
WHERE Invoices.InvoiceID = Invoicelineitems.InvoiceID)
AS InvoiceDate
InvoiceLineItemAmount
FROM InvoiceLineItems
WHERE VendorID = 122
ORDER BY InvoiceDate
在這一切取決於你的需求是什麼結束。
什麼是表格定義?我們需要猜測哪些列當前屬於哪個表以及基數。 – 2013-02-16 23:04:10