title: Using Derived Tables and CTEs to Display Details?
body: <p>I am teaching myself T-SQL and am struggling to comprehend the following example..</p>
  
  <blockquote>
    <p>Suppose you want to display several nonaggregated columns along with
    some aggregate expressions that apply to the entire result set or to a
    larger grouping level. For example, you may need to display several
    columns from the Sales.SalesOrderHeader table and calculate the
    percent of the TotalDue for each sale compared to the TotalDue for all
    the customer’s sales. If you group by CustomerID, you can’t include
    other nonaggregated columns from Sales.SalesOrderHeader unless you
    group by those columns. To get around this, you can use a derived
    table or a CTE.</p>
  </blockquote>
  
  <p>Here are two examples given...</p>
  
  <pre><code>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;
  </code></pre>
  
  <p>Why doesn't this query produce the same result..</p>
  
  <pre><code>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
  </code></pre>
  
  <p>I'm looking for someone to explain the above examples in another way or step through it logically so I can understand how they work?</p>