Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I consider as a good practice to use sub-queries allowing to reduce the overall number of joining operations and the amount of the columns in the block GROUP BY. Therefore, I will tell you at once that the first query is definitely more efficient.</p> <p><strong>Queries:</strong></p> <pre><code>SELECT t.OrderYear , t.CustomerID , t.CustomerOrderAmt , p.FirstName , p.LastName FROM ( SELECT OrderYear = YEAR(OrderDate) , CustomerID , CustomerOrderAmt = COUNT(CustomerID) FROM Sales.SalesOrderHeader GROUP BY YEAR(OrderDate) , CustomerID HAVING COUNT(CustomerID) &gt; 1 ) t JOIN ( SELECT p.FirstName , p.LastName , c.CustomerID FROM Person.Person p JOIN Sales.Customer c ON c.PersonID = p.BusinessEntityID ) p ON t.CustomerID = p.CustomerID ORDER BY t.OrderYear , t.CustomerID </code></pre> <p>vs</p> <pre><code>SELECT Orderdate = YEAR(so.OrderDate) , so.CustomerID , CustomerOrderAmt = COUNT(so.CustomerID) , FirstName = MAX(p.FirstName) , LastName = MAX(p.LastName) FROM Sales.SalesOrderHeader so JOIN Sales.Customer c ON so.CustomerID = c.CustomerID JOIN Person.Person p ON c.PersonID = p.BusinessEntityID GROUP BY YEAR(so.OrderDate) , so.CustomerID HAVING COUNT(so.CustomerID) &gt; 1 </code></pre> <p><strong>Query cost:</strong></p> <p><img src="https://i.stack.imgur.com/M901V.png" alt="Query cost"></p> <p><strong>Execution time:</strong></p> <pre><code>-- first query SQL Server Execution Times: CPU time = 94 ms, elapsed time = 395 ms. -- second query SQL Server Execution Times: CPU time = 140 ms, elapsed time = 480 ms. </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload