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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Multiple cols instead of rows

Status
Not open for further replies.

graabein

Programmer
Oct 9, 2002
186
NO
Hi all,

I have a question. I want my resulting table to have the cols "sum1" "sum2" "sum3" instead of a table with one column "tYear" and one column "tSum".

Example:

tYear tSum
2003 480
2002 270
2001 420

-->

sum1 sum2 sum3
480 270 420

This should be pretty easy.. but how do I do it?

Thanks,
graabein
 
Yes, one more thing, I want to specify which years I want for sum1..3! :)
 
select
sum(case when tyear = 2003 then tsum else 0 end) as sum1,
sum(case when tyear = 2002 then tsum else 0 end) as sum2,
sum(case when tyear = 2001 then tsum else 0 end) as sum3
from table;

If you want it dynamically created, it's more complicated...
Dieter
 
select (select sum(c) from t where tYear = 2001) as sum1,
(select sum(c) from t where tYear = 2002) as sum2,
(select sum(c) from t where tYear = 2003) as sum3

It depends on which DBMS you are using if you can omit the from clause( it is not allowed in ANSI sql, which have a different syntax for just selecting scalar values but which is unsupported by most DBMS). If not, you can create a dummy table with just one row. Many systems have a predefined table for this such as dual in Oracle.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top