Click here to Skip to main content
15,909,091 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to find average of values in each column and then i want to store average values in rows. how to do it?
something like
col1 col2 col3
3 4 5
5 5 6


As you can see
average of col1 is 4
average of col2 is 4.5
average of col3 is 5.5


Now i want the average values to be stored in rows
avg1 4
avg2 4.5
avg3 5.5
Posted
Updated 24-Nov-15 8:43am
v2
Comments
Maciej Los 24-Nov-15 14:45pm    
Based on what condition?

Learn to use PIVOT and UNPIVOT[^].
 
Share this answer
 
v2
Comments
Maciej Los 24-Nov-15 14:46pm    
5ed!
Another option is to use UNION ALL[^].
SQL
SELECT ColName, AvgValue
FROM (
    SELECT 'Avg1' AS ColName, AVG(Col1) As AvgValue
    FROM TableName
    UNION ALL
    SELECT 'Avg2' AS ColName, AVG(Col2) As AvgValue
    FROM TableName
    UNION ALL
    SELECT 'Avg3' AS ColName, AVG(Col3) As AvgValue
    FROM TableName
) AS T


Tested example: SqlFiddle[^]
 
Share this answer
 
v2
Comments
Peter Leow 24-Nov-15 21:04pm    
Brilliant! 5ed.
Maciej Los 25-Nov-15 2:14am    
Thank you, Peter.
BTW: i do not see your 5 ;(
use PIVOT functionality of sql server, it is easy and simple
 
Share this answer
 
Comments
Maciej Los 25-Nov-15 2:15am    
This was mentioned in soultion 1...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900