Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 

SQLStudies

My name is Kenneth Fisher and I am Senior DBA for a large (multi-national) insurance company. I have been working with databases for over 20 years starting with Clarion and Foxpro. I’ve been working with SQL Server for 12 years but have only really started “studying” the subject for the last 3. I don’t have any real "specialities" but I enjoy trouble shooting and teaching. Thus far I’ve earned by MCITP Database Administrator 2008, MCTS Database Administrator 2005, and MCTS Database Developer 2008. I’m currently studying for my MCITP Database Developer 2008 and should start in on the 2012 exams next year. My blog is at www.sqlstudies.com.

Using CROSS APPLY to calculate an aggregate across a single row.

I’ve had CROSS APPLY on the mind recently. You could probably tell since its been the subject of my last two posts. Since it’s been on my mind a lot I started to wonder if I could use it to solve some problems I’ve run across in the past. In this particular case running an aggregate, say a max, over multiple columns in a row.

For example let’s say I have a table as follows.

CREATE TABLE QuarterlyAverages (
[Year] smallint,
[Q1Average] money,
[Q2Average] money,
[Q3Average] money,
[Q4Average] money)

Yes I realize it’s denormalized, but first it’s an example and second I’ve seen tables similar to this in the real world.

Given that table, I am tasked to produce the highest quarterly average per year. Previously I would have written something complicated and annoying using lots of cases. Using CROSS APPLY however I can do this.

SELECT [Year], MAX(Quarters.Average)
FROM QuarterlyAverages
CROSS APPLY (VALUES 
		(1, [Q1Average]),
		(2, [Q2Average]),
		(3, [Q3Average]),
		(4, [Q4Average]) ) Quarters (Q, Average)
GROUP BY [Year]

I have to admit I love it when I find a smooth solution for problems I’ve struggled with in the past!


Filed under: Microsoft SQL Server, SQLServerPedia Syndication, T-SQL Tagged: code language, CROSS APPLY, language sql, microsoft sql server, sql statements, T-SQL

Comments

Leave a comment on the original post [sqlstudies.com, opens in a new window]

Loading comments...