| Author |
Topic |
|
erica686
Starting Member
13 Posts |
Posted - 2009-11-29 : 23:56:18
|
| Hi there, I have a table as follows:PERSON_CODE, DR_CR, AMOUNTJKM, D, 10JKM, C, 2.5ALK, C, 6.9ION, C, 79ALK, D, 80ALK, D, 786ION, C, 23I need to sum the transaction lines, however 'D' lines must be converted to negative beforehand. Normally I would just select all transactions, change 'D' to negative, and then group the transactions in my report to create a sum total. Is there any way that I can achieve this same result in the SQL query?Eg: PERSON_CODE, SUM_AMOUNTJKM, 7.5ALK, -859.1ION, 102Thanks |
|
|
kbhere
Yak Posting Veteran
58 Posts |
Posted - 2009-11-30 : 00:28:27
|
| SELECT PERSON_CODE, (SELECT SUM(AMOUNT) FROM Table WHERE DR_CR LIKE 'C') - (SELECT SUM(AMOUNT) FROM Table WHERE DR_CR LIKE 'D')FROM TableBalaji.K |
 |
|
|
erica686
Starting Member
13 Posts |
Posted - 2009-11-30 : 01:05:27
|
| Thanks, that is almost working.Using the example below, that query is giving me:JKM,749.6ALK,749.6ION,749.6instead of grouping the sum transactions by the person code:JKM, 7.5ALK, -859.1ION, 102 |
 |
|
|
bklr
Master Smack Fu Yak Hacker
1693 Posts |
Posted - 2009-11-30 : 01:15:09
|
try like thisDECLARE @t table (PERSON_CODE varchar(32), DR_CR varchar(32), AMOUNT decimal(18,2))insert into @t select 'JKM', 'D', 10 union all select 'JKM', 'C', 2.5 union all select 'ALK', 'C', 6.9 union all select 'ION', 'C', 79 union all select 'ALK', 'D', 80 union all select 'ALK', 'D', 786 union all select 'ION', 'C', 23select distinct t.person_code, ISNULL(cr,0)-ISNULL(dr,0)as sum_amountfrom @t tLEFT join (Select person_code,sum(amount) as dr from @t where dr_cr ='d' group by person_code) d on d.person_code = t.person_codeLEFT join (Select person_code,sum(amount) as cr from @t where dr_cr ='c' group by person_code) c on c.person_code = t.person_code |
 |
|
|
kbhere
Yak Posting Veteran
58 Posts |
Posted - 2009-11-30 : 01:50:30
|
quote: Originally posted by erica686 Thanks, that is almost working.Using the example below, that query is giving me:JKM,749.6ALK,749.6ION,749.6instead of grouping the sum transactions by the person code:JKM, 7.5ALK, -859.1ION, 102
That was the basic idea.. You can alter that as per your need..All the Best..With Regards,Balaji.K |
 |
|
|
|
|
|