2013-02-16 73 views
2

作爲一項練習任務,我正在尋找將聯接重寫爲select子句中的子查詢。我明白select語句中的一個子查詢必須返回一個單一的值,我很難弄清楚如何以一種合理的方式重寫它。在select語句中重新將關聯子查詢重新加入查詢

這裏的原始連接聲明:

SELECT InvoiceNumber, InvoiceDate, InvoiceLineItemAmount 
FROM Invoices JOIN InvoiceLineItems 
    ON Invoices.InvoiceID = Invoicelineitems.InvoiceID 
WHERE VendorID = 122 
ORDER BY InvoiceDate 

任何提示或幫助將不勝感激!

+2

什麼是表格定義?我們需要猜測哪些列當前屬於哪個表以及基數。 – 2013-02-16 23:04:10

回答

1

我的提示是在您的子查詢的主要查詢和發票中有InvoiceLineItems。這會增加讓子查詢返回一行的可能性。

+0

+1假設這種關係對於許多行項目是1張發票,這將起作用。 '從發票'的答案不會。 – 2013-02-16 23:07:22

0

如果在子查詢多行多,那麼你需要,而不是使用ON條款您只需將條件的子查詢WHERE子句中的TOP條款

SELECT InvoiceNumber, InvoiceDate, 
(
    SELECT InvoiceLineItemAmount 
    FROM InvoiceLineItems 
    WHERE Invoices.InvoiceID = Invoicelineitems.InvoiceID 
) AS InvoiceLineItemAmount 
FROM Invoices 
WHERE VendorID = 122 
ORDER BY InvoiceDate 
+0

想再看看你寫的是什麼?請特別注意「聯合」一詞後的含義。 – 2013-02-16 23:09:16

+0

ooops。 Removed .. – 2013-02-16 23:12:36

1

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 

在這一切取決於你的需求是什麼結束。

+0

很多選項,但它們都沒有'FROM InvoiceLineItems'作爲主要查詢和'FROM Invoices'作爲相關的子查詢。通過這種方式,假設'InvoiceID'是'Invoices'的PK,並且有一個用於防止孤行的項目的外鍵,那麼只能有一個匹配的行。 – 2013-02-16 23:13:38

+0

+1我認爲我們可以做出一個有根據的猜測,即「發票」表不可能有多於一行並具有相同的「InvoiceID」 – 2013-02-16 23:32:53

+0

我認爲這是一個很好的假設,但是,我已經看到了更瘋狂的東西狂野。 – pyrospade 2013-02-17 00:00:55