Hello Everyone,
I am having difficulty figuring out how to do a query that averages some of the columns of my result set and making that average part of the result.
Here is an example of what I'm talking about. Let's say I have four records on MyTable, as follows:
ProgramName BusinessUnit Q1Rev Q2Rev Q3Rev Q4Rev
----------- ------------ ----- ----- ----- -----
P1 BU1 10 10 0 0
P2 BU1 0 10 10 0
P3 BU2 0 0 10 10
P4 BU2 0 0 10 10
When I run this query:
SELECT BusinessUnit, Sum(Q1Rev) as Q1, Sum(Q2Rev) as Q2, Sum(Q3Rev) as Q3, Sum(Q4Rev) as Q4
FROM MyTable
GROUP BY BusinessUnit
I get the following results:
BusinessUnit Q1 Q2 Q3 Q4
------------ -- -- -- --
BU1 10 20 10 0
BU2 0 0 20 20
What I want to be able to due is add a final column called AvgAnnualRev that has the following results:
BusinessUnit Q1 Q2 Q3 Q4 AvgAnnualRev
------------ -- -- -- -- ------------
BU1 10 20 10 0 53.333
BU2 0 0 20 20 80
AvgAnnual is calculated by taking the average of the NON-ZERO quarterly revenue totals (to get the average quarterly revenue), then multiplying by 4 to get the average annual revenue.
So, the result for BU1 is ((10 + 20 + 10) / 3) * 4 = 53.333
And the result for BU2 is ((20 + 20) / 2) * 4 = 80
My question is, how do I do this in SQL? As it stands, I end up having to put the results of my first query (without AvgAnnualRev) into a spreadsheet and then manually use my spreadsheet program to calculate the AvgAnnualRev column.
Thanks in advance for any help!
clakerley
I am having difficulty figuring out how to do a query that averages some of the columns of my result set and making that average part of the result.
Here is an example of what I'm talking about. Let's say I have four records on MyTable, as follows:
ProgramName BusinessUnit Q1Rev Q2Rev Q3Rev Q4Rev
----------- ------------ ----- ----- ----- -----
P1 BU1 10 10 0 0
P2 BU1 0 10 10 0
P3 BU2 0 0 10 10
P4 BU2 0 0 10 10
When I run this query:
SELECT BusinessUnit, Sum(Q1Rev) as Q1, Sum(Q2Rev) as Q2, Sum(Q3Rev) as Q3, Sum(Q4Rev) as Q4
FROM MyTable
GROUP BY BusinessUnit
I get the following results:
BusinessUnit Q1 Q2 Q3 Q4
------------ -- -- -- --
BU1 10 20 10 0
BU2 0 0 20 20
What I want to be able to due is add a final column called AvgAnnualRev that has the following results:
BusinessUnit Q1 Q2 Q3 Q4 AvgAnnualRev
------------ -- -- -- -- ------------
BU1 10 20 10 0 53.333
BU2 0 0 20 20 80
AvgAnnual is calculated by taking the average of the NON-ZERO quarterly revenue totals (to get the average quarterly revenue), then multiplying by 4 to get the average annual revenue.
So, the result for BU1 is ((10 + 20 + 10) / 3) * 4 = 53.333
And the result for BU2 is ((20 + 20) / 2) * 4 = 80
My question is, how do I do this in SQL? As it stands, I end up having to put the results of my first query (without AvgAnnualRev) into a spreadsheet and then manually use my spreadsheet program to calculate the AvgAnnualRev column.
Thanks in advance for any help!
clakerley