我正在自学 T-SQL,并且正在努力理解以下示例。
假设您想要显示几个非聚合列以及一些应用于整个结果集或更大分组级别的聚合表达式。例如,您可能需要显示 Sales.SalesOrderHeader 表中的几列,并计算每个销售的 TotalDue 与所有客户销售的 TotalDue 的百分比。如果按 CustomerID 分组,则不能包含 Sales.SalesOrderHeader 中的其他非聚合列,除非按这些列分组。为了解决这个问题,您可以使用派生表或 CTE。
这里给出了两个例子......
SELECT c.CustomerID, SalesOrderID, TotalDue, AvgOfTotalDue,
TotalDue/SumOfTotalDue * 100 AS SalePercent
FROM Sales.SalesOrderHeader AS soh
INNER JOIN
(SELECT CustomerID, SUM(TotalDue) AS SumOfTotalDue,
AVG(TotalDue) AS AvgOfTotalDue
FROM Sales.SalesOrderHeader
GROUP BY CustomerID) AS c ON soh.CustomerID = c.CustomerID
ORDER BY c.CustomerID;
WITH c AS
(SELECT CustomerID, SUM(TotalDue) AS SumOfTotalDue,
AVG(TotalDue) AS AvgOfTotalDue
FROM Sales.SalesOrderHeader
GROUP BY CustomerID)
SELECT c.CustomerID, SalesOrderID, TotalDue,AvgOfTotalDue,
TotalDue/SumOfTotalDue * 100 AS SalePercent
FROM Sales.SalesOrderHeader AS soh
INNER JOIN c ON soh.CustomerID = c.CustomerID
ORDER BY c.CustomerID;
为什么这个查询不产生相同的结果..
SELECT CustomerID, SalesOrderID, TotalDue, AVG(TotalDue) AS AvgOfTotalDue,
TotalDue/SUM(TotalDue) * 100 AS SalePercent
FROM Sales.SalesOrderHeader
GROUP BY CustomerID, SalesOrderID, TotalDue
ORDER BY CustomerID
我正在寻找有人以另一种方式解释上述示例或逻辑地逐步解释它们,以便我可以理解它们是如何工作的?