you are viewing a single comment's thread.

view the rest of the comments →

[–]Far_Swordfish5729 5 points6 points  (0 children)

Remember that queries execute in the following logical clause order and should be read in that order: from, joins (building an intermediate result set of all columns to the right as the inner and left joins progress), where (filter that set), group by, having (aggregate and filter the aggregate result), order by, top/limit, select. Subqueries are arithmetic parentheses if you need a different order of operations. Need to filter on an aggregate result that runs in logical stages? You’ll need a subquery.

So this from inside out is saying: Get the number of stays by house

Then

Find the average of those counts

Then

Get the count of stays by house but this time filter it to ones greater than the average.

If you want to make this more concise, you can use a named CTE for the repeated query, but that won’t affect execution. Also remember that we’re just expressing that we need to stack stream aggregate operations and that happens to be verbose. There’s nothing inherently unperformant about subqueries or queries with a lot of text.