Author |
Topic |
Burzy
Starting Member
6 Posts |
Posted - 2012-06-26 : 16:34:11
|
Hi!I have problem with query. I have table:client_ID | account_DT | account_CT | amount 1 | 21 | 50 | 100 2 | 21 | 34 | 300 1 | 45 | 21 | 500 3 | 30 | 50 | 360And I want to get account balance of certain account, for example 21:Client_ID | Balance 1 | -400 2 | 300I can do that with union, but I'd like to know other way.How can I get such result?Thank You for Your advice! |
|
TG
Master Smack Fu Yak Hacker
6065 Posts |
Posted - 2012-06-26 : 16:54:14
|
Here's one way:declare @accountid intset @accountid = 21;with yourTable (client_ID, account_DT, account_CT, amount)as (select 1 , 21 , 50 , 100 union allselect 2 , 21 , 34 , 300 union allselect 1 , 45 , 21 , 500 union allselect 3 , 30 , 50 , 360)select client_id ,sum(case when account_dt = @accountid then amount when account_ct = @accountid then amount * -1 else 0 end) as Balancefrom yourTablewhere account_DT = @accountidor account_CT = @accountidgroup by client_idOUTPUT:client_id Balance----------- -----------1 -4002 300 Be One with the OptimizerTG |
 |
|
Burzy
Starting Member
6 Posts |
Posted - 2012-06-27 : 01:18:21
|
Thanks for that, its working! But I have another problem. I have same table as previous and another one with latest operations for certain ID.Something like that:MyTable2Client_ID, account_DT, account_CT, amount1, 30, 21, 5002, 21, 40, 3004, 15, 21, 50As previously, I want to get balance of account 21 but with with these 2 tables.Example:Client_id, Balance1, -9002, 6004, -50How query should be writen to get such result? |
 |
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2012-06-27 : 03:29:29
|
[code]select client_id ,sum(case when account_dt = @accountid then amount when account_ct = @accountid then amount * -1 else 0 end) as Balancefrom ( select client_ID, account_DT, account_CT, amount from MyTable1 union all select client_ID, account_DT, account_CT, amount from MyTable2) twhere account_DT = @accountidor account_CT = @accountidgroup by client_id[/code] KH[spoiler]Time is always against us[/spoiler] |
 |
|
Burzy
Starting Member
6 Posts |
Posted - 2012-06-27 : 04:52:01
|
That's all what I want to know. Thanks again! :) |
 |
|
|
|
|