SQL Server中的派生表

时间:2014-02-19 18:36:46

标签: sql sql-server derived-table

我有这两个问题。我不知道如何将它们组合在一起来制作派生表。我想使用第二个查询作为主查询,并使用主查询的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;

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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