This month’s T-SQL Tuesday #026 hosted by David Howard asked people to take on a wide open task, to write about any of the previous 25 topics. Having so many to choose from should have made it easy, but instead it was harder. I could have done something with each topic since it seems that reading the old blogs only sparked more new ideas.
Instead of going to the past, I decided to go to the future and write about the new features in SQL Server 2012 that will help us with aggregation, a subject that should be close on any BI developer’s mind. I chose the topic because of T-SQL #016 by Jes Borland on Aggregations since there are going to be some interesting new functions to help us aggregate better.
Windows in T-SQL
The Windowing functions (which have nothing to do with Windows) in the upcoming version of SQL Server let us do in one query Analytic calculations that include sliding aggregations, standard deviations, and more. This way we can compare averages, sums, and other numbers using preceding and current rows in a much cleaner, simpler way than we can today.
SELECT OrderDateKey, DailySales,
WeekAvgCurrent = AVG(DailySales)
OVER (ORDER BY OrderDateKey ROWS BETWEEN 6 PRECEDING AND CURRENT ROW),
WeekAvg1WeekAgo = AVG(DailySales)
OVER (ORDER BY OrderDateKey ROWS BETWEEN 13 PRECEDING AND 7 PRECEDING),
WeekDiff = AVG(DailySales)
OVER (ORDER BY OrderDateKey ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) – AVG(DailySales) OVER (ORDER BY OrderDateKey ROWS BETWEEN 13 PRECEDING AND 7 PRECEDING),
WeekStdDev = STDEV(DailySales)
OVER (ORDER BY OrderDateKey ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)
FROM (SELECT f.OrderDateKey, SUM(SalesAmount) as DailySales
FROM FactInternetSales f
inner join DimDate dd on dd.DateKey = f.OrderDateKey
where dd.CalendarYear = 2003
group by f.OrderDateKey) as DailyTable
order by OrderDateKey
The query produces this result from AdventureWorksDW. Only the first 12 rows are shown and I modified the column titles slightly for readability:
|Order Date Key||Daily Sales||This Week Avg||Last Week Avg||Difference Week-to-Week||This Week Std Dev|
The results show you that we can get the average sales for the last 7 days, the sales for the 7 days before that, compare the two to get the difference between the last two weeks, and the standard deviation for the week.
All in one fairly simple straightforward query. Very powerful.