Window Functions
Window functions are a very powerful part of the SQL language. They are often the most efficient way to solve problems—this is especially true when the window function is the “natural” method for doing a calculation. They can also be used in clever ways.
Where Window Functions Are Appropriate
What proportion of a state's population lives in each zip code? This query can be answered using “traditional” SQL using a join and an aggregation:
SELECT zc.zcta5, zc.TotPop / s.StatePop FROM ZipCensus zc JOIN (SELECT zc.Stab, SUM(1.0 * zc.TotPop) as StatePop FROM ZipCensus zc GROUP BY zc.Stab ) s ON zc.Stab = s.Stab
Although readily expressed in traditional SQL, this is not the best way to answer this question.
One problem with this approach is evident if filtering is needed. Say we were to add a WHERE clause to choose a single state: WHERE stab = 'MA'. The subquery would still process the data for all...