Solved

Calc Average Value for Values in Row of Matrix

Posted on 2007-11-21
978 Views
I've have a returns matrix set up and I'd like to calculate the average values across a row.  Are there any built-in functions to do something like this?  I'll need to account for nulls etc.  Max there would be 12 columns of data.

Ex:
2,5,4, null are all the values in a row so the avg would be 3.66

Thanks!
0
Question by:gigglick
• 4
• 2
• 2

LVL 69

Accepted Solution

ScottPletcher earned 500 total points
ID: 20329017
No, nothing built in, you will have to code it yourself:

SELECT ...,
(ISNULL(col1, 0) + ISNULL(col2, 0) + ... + ISNULL(col12, 0) /
NULLIF(
(CASE WHEN col1 IS NULL THEN 0 ELSE 1 END +
CASE WHEN col2 IS NULL THEN 0 ELSE 1 END +
... +
CASE WHEN col12 IS NULL THEN 0 ELSE 1 END), 0) AS AvgAcrossCols,
...
0

LVL 6

Expert Comment

ID: 20329050
" Max there would be 12 columns of data."

Is there a variable number of columns displayed?
0

LVL 5

Author Comment

ID: 20329098
Hi - didn't think there was anything built - DARN!  The storage table for the matrix will always have twelve columns, however, not all accounts on our end will have enough data to fill all twelve columns of the matrix.  Also, I am giving the user the option to choose the number of periods/columns they want.  So the problem is substituting 0 in for null will result in the wrong average.
0

LVL 69

Expert Comment

ID: 20329119
Not with the code I posted it won't :-).  When I divide to get the average, I *don't count* those that are NULL, only those that aren't NULL.
0

LVL 6

Expert Comment

ID: 20329130
Scotts answer should work if there are a fixed number of columns.
0

LVL 5

Author Comment

ID: 20329185
Hi Scott -
I should have mentioned that I wasn't directing that at your reponse...but code I was toying with on my end.  I'm trying yours out now...

Giggs
0

LVL 5

Author Comment

ID: 20330024
Hi Scott -

Worked perfectly and quick!! Thanks so much for your help.

Giggs
0

LVL 5

Author Closing Comment

ID: 31410402
How does he always get it right?
0

Featured Post

When you hear the word proxy, you may become apprehensive. This article will help you to understand Proxy and when it is useful. Let's talk Proxy for SQL Server. (Not in terms of Internet access.) Typically, you'll run into this type of problem w…
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function