2014-02-19 94 views
0

我有這兩個查詢。我不知道如何將它們結合在一起製作派生表。我假設使用第二個查詢作爲主查詢,並在主查詢的FROM子句中使用第一個查詢。SQL Server中的派生表

SELECT EmailAddress, Orders.OrderID, SUM(ItemPrice * Quantity) AS OrderTotal 
FROM Customers 
JOIN Orders ON Customers.CustomerID = Orders.CustomerID 
JOIN OrderItems ON Orders.OrderID = OrderItems.OrderID 
GROUP BY EmailAddress, Orders.OrderID; 

SELECT EmailAddress, MAX(ItemPrice) as LargestOrder 
FROM Customers 
JOIN Orders ON Customers.CustomerID = Orders.CustomerID 
JOIN OrderItems ON Orders.OrderID = OrderItems.OrderID 
GROUP BY EmailAddress 
+0

什麼是你正在試圖做的查詢? – 2014-02-19 18:41:29

+0

您是否試圖獲得由客戶提供的單筆訂單總額或總額訂單總額的最大值? – Miller

+0

我試圖將兩個查詢的結果合併到一個表中 – jaramore

回答

2

你只是想讓結果在同一張表中嗎?只是這樣做:

SELECT FirstTable.*, SecondTable.LargestOrder 
FROM (
    SELECT EmailAddress, Orders.OrderID, SUM(ItemPrice * Quantity) AS OrderTotal 
    FROM Customers 
    JOIN Orders ON Customers.CustomerID = Orders.CustomerID 
    JOIN OrderItems ON Orders.OrderID = OrderItems.OrderID 
    GROUP BY EmailAddress, Orders.OrderID) as FirstTable 
JOIN (
    SELECT EmailAddress, MAX(ItemPrice) as LargestOrder 
    FROM Customers 
    JOIN Orders ON Customers.CustomerID = Orders.CustomerID 
    JOIN OrderItems ON Orders.OrderID = OrderItems.OrderID 
    GROUP BY EmailAddress) as OtherTable ON FirstTable.EmailAddress = OtherTable.EmailAddress 
+0

謝謝!它現在有效 – jaramore

1

你可以使用「窗口功能」代替像這樣

SELECT DISTINCT 
    EmailAddress, 
    Orders.OrderID, 
    SUM(ItemPrice * Quantity) OVER (PARTITION BY EmailAddress, Orders.OrderID) AS OrderTotal, 
    MAX(ItemPrice) OVER (PARTITION BY EmailAddress) AS LargestOrder 
FROM Customers 
JOIN Orders ON Customers.CustomerID = Orders.CustomerID 
JOIN OrderItems ON Orders.OrderID = OrderItems.OrderID 

否則,您可以將合併這兩個查詢到每一個自己的公共表表達式和那些一起加入同時選擇。

WITH Total AS (
    SELECT EmailAddress, Orders.OrderID, SUM(ItemPrice * Quantity) AS OrderTotal 
FROM Customers 
JOIN Orders ON Customers.CustomerID = Orders.CustomerID 
JOIN OrderItems ON Orders.OrderID = OrderItems.OrderID 
GROUP BY EmailAddress, Orders.OrderID 
), Largest AS (

SELECT EmailAddress, MAX(ItemPrice) as LargestOrder 
FROM Customers 
JOIN Orders ON Customers.CustomerID = Orders.CustomerID 
JOIN OrderItems ON Orders.OrderID = OrderItems.OrderID 
GROUP BY EmailAddress 
) 
SELECT Total.EmailAddress, Total.OrderId, OrderTotal, LargestOrder 
FROM Total 
INNER JOIN Largest ON Total.EmailAddress = Largest.EmailAddress