sql server - Calculate sum in SQL and display it as another column? -


i used following query calculating credit of customers problem want calculate sum of credit column in sum credit , display in column .is there way of doing modifying following query? highly appreciable.

select     customer_name    ,todays_total    ,amount_recieved    ,date_sale    ,item_model    ,quantity    ,credit = (case        when amount_recieved=0 , todays_total>0 , credit =0 todays_total        when amount_recieved>0 , todays_total>0 , credit>=0 (credit+todays_total)-amount_recieved       when amount_recieved>0 , todays_total=0 , credit >0 (credit-amount_recieved)       end)  customer_credit_records  customer_name='saad ned' 

first, here query more understandably formatted:

select customer_name, todays_total, amount_recieved, date_sale, item_model, quantity,        credit = (case when amount_recieved=0 , todays_total>0 , credit=0                       todays_total                        when amount_recieved>0 , todays_total>0 , credit>=0                       (credit+todays_total)-amount_recieved                       when amount_recieved>0 , todays_total=0 , credit>0                       (credit-amount_recieved)                  end)  customer_credit_records customer_name = 'saad ned'; 

you have 1 customer, of columns don't make sense daily total. can do:

select customer_name,         sum(case when amount_recieved=0 , todays_total>0 , credit=0                 todays_total                  when amount_recieved>0 , todays_total>0 , credit>=0                 (credit+todays_total)-amount_recieved                 when amount_recieved>0 , todays_total=0 , credit>0                 (credit-amount_recieved)            end) credit customer_credit_records customer_name = 'saad ned' group customer_name; 

however, i'm curious arithmetic in case statements. have aversion adding values 0? seems simpler do:

select customer_name,         sum(credit + todays_total - amount_recieved) credit customer_credit_records customer_name = 'saad ned' group customer_name; 

this assumes @ least 1 of when conditions satisfied.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -