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

summing the same field twice 2

Status
Not open for further replies.

rasayldz

Programmer
Dec 15, 2003
4
TR
Hi
i have a table like this:

customer code amount
-------- ---- ------
x 1 5
x 1 10
x 2 20
x 2 15
-----------------

"amount" has different meanings depending on the "code" and i want to get sum of the "amount" for both code=1 and code=2 . Is this possible with one SQL statement?

Thanks in advance,

Rasa

ps: i am on DB/2 for iseries...
 
[tt]select customer
, sum(case when code=1
then amount
else null end) as code1sum
, sum(case when code=2
then amount
else null end) as code2sum
from yourtable
group
by customer[/tt]

rudy
 
select distinct code, sum(amount)
from yourtable
group by code;

This is more flexible and avoids hardcoding of code values, useful esp. if column 'code' can have multiple values.
 
rrrkrishnan, your query is of course the most general, but it is not necessarily the most flexible

specifically, rasa said "amount" has different meanings depending on the "code"

suppose the query was supposed to accumulate 80% of the amount for code 1 items and 90% of the amount for code 2 items, then my query can flexibly be altered like this:

[tt]select customer
, sum(case when code=1
then amount * 0.8
else null end) as code1sum
, sum(case when code=2
then amount * 0.9
else null end) as code2sum
from yourtable
group
by customer[/tt]

and voila, it's done

whereas yours is not quite so flexible

;-)

rudy

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top