Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Return column names in one column of a query

Status
Not open for further replies.

DomTrix

Programmer
Dec 28, 2004
94
GB
Hi there, I have a table with 8 integer columns and I want to return the average value for each column in a single query.

I can do it easily enough with 8 columns but I would like the query to contain only two columns, 'columnName' and 'average'.

Is this possible?

Thanks, dom
 
DOh, ignore me, I can use COLLATE of course
 
Union???

create table test (col1 int,col2 int,col3 int,col4 int)
insert into test
select 1,2,3,4 union all
select 11,2,3,4 union all
select 1,22,3,4 union all
select 1,52,63,4 union all
select 1,2,3,1004

select avg(col1) as col1,avg(col2) as Col2,avg(col3) as col3,avg(col4) as Col4
from test

drop table test

Denis The SQL Menace
SQL blog:
Personal Blog:
 
Yah, that would bring out results like:
Code:
col1  col2  col3  col4
4.5   2.3   6.7   2.6

I needed results like

Code:
colName  average
 'col1'   4.5
 'col2'   2.3
 'col3'   6.7
 'col4'   2.6

Can be achieved with a union:

Code:
SELECT avg(col1) as average,
       'col1' as colName

UNION ALL

SELECT avg(col2) as average,
       'col2' as colName

....etc

Thankyou tho
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top