我正在尝试构建以下查询:
SELECT
COUNT(dbo.[Order].OrderID) AS Orders,
SUM(dbo.OrderLine.SubTotal) + SUM(dbo.OrderLine.Shipping) - SUM(dbo.OrderLine.Discount) AS Revenue,
SUM(dbo.OrderLine.Shipping) AS Expr1,
DATEADD(dd, 0, DATEDIFF(dd, 0, dbo.[Order].PaymentDate)) AS RevenueDate,
(SUM(dbo.OrderLine.SubTotal) + SUM(dbo.OrderLine.Shipping)) / COUNT(dbo.[Order].OrderID) AS RevenuePerOrder,
SUM(dbo.OrderLine.Qty) AS Qty
FROM
dbo.[Order]
INNER JOIN dbo.OrderLine ON dbo.[Order].OrderID = dbo.OrderLine.OrderID
INNER JOIN (
SELECT SUM(dbo.OrderLine.SubTotal) + SUM(dbo.OrderLine.Shipping) - SUM(dbo.OrderLine.Discount) AS BulkRevenue
FROM dbo.OrderLine
INNER JOIN dbo.[Order] ON dbo.OrderLine.OrderID = dbo.[Order].OrderID
WHERE BulkOrder = 1) bulkrevenue
WHERE (dbo.[Order].OrderStatusID IN (2))
AND (dbo.[Order].PaymentDate >= CONVERT(DATETIME, '02/03/2014', 103))
AND (dbo.[Order].PaymentDate <= CONVERT(DATETIME, '08/03/2014', 103))
AND (dbo.[Order].WebsiteID = 2)
GROUP BY DATEADD(dd, 0, DATEDIFF(dd, 0, dbo.[Order].PaymentDate)), dbo.[Order].WebsiteID
Sub Query / second INNER JOIN是事情失败的地方,这是我可以做的事情吗?我希望将批量订单收入作为同一结果集中的另一列。
希望这是有道理的。
谢谢,
迈克尔
答案 0 :(得分:2)
看起来您没有为第二次内部联接指定加入哪个键。
INNER JOIN (
SELECT SUM(dbo.OrderLine.SubTotal) + SUM(dbo.OrderLine.Shipping) - SUM(dbo.OrderLine.Discount) AS BulkRevenue
FROM dbo.OrderLine
INNER JOIN dbo.[Order] ON dbo.OrderLine.OrderID = dbo.[Order].OrderID
WHERE BulkOrder = 1) bulkrevenue ON bulkrevenue.___ = table.____
这可能是外部申请或交叉申请更符合您需求的情况(我相信您当前的总和操作对于每一行都显示相同,不确定是否有意)请参阅http://sqlserverplanet.com/sql-2005/cross-apply-explained