April 1, 2002 at 12:50 pm
Hi, All
I have a Q for U.
I though this was easy to do but not quite..
Here is one..
ID Code Amount
1 AA 120.00
1 AB 30.00
1 CA 25.00
1 CB 5.00
1 DA 10.00
1 DB 15.00
1 EA 45.00
1 EB 100.00
I want to do this cal..(AA+CA)-(DA+DB+EA)
Any idea?
Thx in advance.
Jay
April 1, 2002 at 1:16 pm
One way would be something like this:
Declare @AA int
Declare @CA int
select @AA=Amount where code='AA'
select @CA=Amount where code='CA'
select @AA+@CA
Andy
April 1, 2002 at 1:30 pm
Hi, Andy..
Thx.. it works for this ID but not other ID who doesnt have DA or DB..
I got Null return..
Any other way?
Jay
April 1, 2002 at 3:06 pm
Try pivoting first then add.
SELECT
[ID]
((AA+CA)-(DA+DB+EA)) AS MyCalc
FROM (
SELECT
[ID],
SUM(CASE CODE WHEN 'AA' THEN Amount ELSE 0 END) AS AA,
SUM(CASE CODE WHEN 'CA' THEN Amount ELSE 0 END) AS CA,
SUM(CASE CODE WHEN 'DA' THEN Amount ELSE 0 END) AS DA,
SUM(CASE CODE WHEN 'DB' THEN Amount ELSE 0 END) AS DB,
SUM(CASE CODE WHEN 'EA' THEN Amount ELSE 0 END) AS EA
FROM
tblX
GROUP BY
[ID]
) AS tblBaseData
Note: You may need to do 0 as 0.00 to keep datatype right or even CAST(0 AS numeric(3,2)) or similar.
"Don't roll your eyes at me. I will tape them in place." (Teacher on Boston Public)
Added END to correct for future reference.
Edited by - antares686 on 04/01/2002 3:23:51 PM
April 1, 2002 at 3:19 pm
Thx..
That really works...
In the code, U missed END after 0 :-)))
Anyway..Thx
Jay
April 1, 2002 at 3:23 pm
Sorry doing this from the top of my head, no server to test against and no analyzer with nice color coding.
"Don't roll your eyes at me. I will tape them in place." (Teacher on Boston Public)
April 2, 2002 at 6:22 pm
To eliminate NULL when summing fields, use isnull(fieldname, 0) so you end up with:
sum(isnull(fieldname, 0))
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply