SQL SUM values where 2 conditions are met - mysql

I am trying to create a query that calculates credit and debit for each month. the values are in column called SUM and there is a field for each record that says if it is credit or debit (ex_type). I have manage to get the total sum of all the fields (although it is not correct as well - cos I am just sum all the values no matter if it is credit or debit).
SELECT sum(sum) as total FROM acc where month='$month'
But I cannot figure out for to do it for Credit and Debit
So, to summarize... I want to have the following two queries combined in one.
1. Select sum(sum) as Debit from acc where ex_type='Debit' and month='$month'
2. Select sum(sum) as Credit from acc where ex_type='Credit' and month='$month'
So, any help is much appreciated.

Try this with CASE
Select sum(CASE WHEN ex_type='Debit' THEN `sum` ELSE 0 END) as Debit,
sum(CASE WHEN ex_type='Credit' THEN `sum` ELSE 0 END) as Credit FROM ...

This should work:
Select sum(d.sum) as Debit,
(Select sum(c.sum) from acc c where c.ex_type='Credit' and c.month='$month') as Credit
from acc d where d.ex_type='Debit' and d.month='$month'
However if you supply more details on other fields one could inner join onto the same table and that may be slightly more efficient.

Maybe duplicate post :
SUM() based on a different condition to the SELECT
Try this :
Select
SUM(CASE WHEN ex_type='Debit' THEN `sum` ELSE 0 END) as Debit,
SUM(CASE WHEN ex_type='Credit' THEN `sum` ELSE 0 END) as Credit
FROM acc
Where etc...

I'm not a MySQL expert, but you might want to try the following
SELECT
SUM(CASE WHEN ex_type='Debit' THEN sum ELSE 0 END CASE) as SumOfDebit,
SUM(CASE WHEN ex_type='Credit' THEN sum ELSE 0 END CASE) as SumOfCredit,
FROM acc
WHERE
month = '$month'
MySQL reference 5.0 deals with the CASE statement if this doesn't work as expected

SELECT
SUM(sum) as total
SUM(IF(ex_type='Debit',sum,0)) Debit
SUM(IF(ex_type='Credit',sum,0)) Credit
FROM acc
WHERE month='$month'

The simplest (and coolest) way is:
SELECT
SUM((ex_type='Debit') * sum) Debit,
SUM((ex_type='Credit') * sum) Credit,
FROM acc
WHERE month = '$month'
This works because in mysql, true is 1 and false is 0.

Related

How to create a calculated row in sql or power bi?

I am trying to do a calculation on 2 rows on a SQL I wrote so I can have a 3 row that will be Profit and show the amount is it possible?
This dummy data not true to any company!
see below :
SELECT a.pcg_type GL_Acoount_Group,
Abs(sum(b.debit-b.credit)) GL_Amount
FROM dolibarr.llx_accounting_account a
JOIN dolibarr.llx_accounting_bookkeeping b
ON a.account_number = b.numero_compte
WHERE a.pcg_type IN ('INCOME', 'EXPENSE')
ANDa.fk_pcg_version = 'PCG99-BASE'
GROUP BY a.pcg_type
Results:
Group. Amt
INCOME 379200
EXPENSE 65700
Expected Results:
Group. Amt
INCOME 379200
EXPENSE 65700
PROFIT 313500
Use ROLLUP for adding an extra row and use CASE statement inside SUM() function for treating expense value as negative for calculation
--MySQL
SELECT COALESCE(acc_type, 'Profit') "Group"
, ABS(SUM(CASE WHEN acc_type = 'EXPENSE' THEN -amount ELSE amount END)) amt
FROM test
GROUP BY acc_type WITH ROLLUP
Another way by using UNION ALL
SELECT acc_type "Group"
, SUM(amount) Amt
FROM test
GROUP BY acc_type
UNION ALL
SELECT 'Profit' AS "Group"
, SUM(CASE WHEN acc_type = 'EXPENSE' THEN -amount ELSE amount END) Amt
FROM test
Please check this url https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=f859036ffcb3d808330bce5346daee1e

Get Available Balance from transaction table using MYSQL

I tried to get available balance of specific account number using SQL QUERY my code is below:
select sum(amount) as Cr form transaction where credit=1 and account_no=2549
Union
select sum(amount) as Dr form transaction where debit=1 and account_no=2549
Difference Cr-Dr
You could use case to get sum for credit and debit in single query as
select sum(case when credit=1 then amount else 0 end) as Cr ,
sum(case when debit=1 then amount else 0 end) Dr,
sum(case when credit=1 then amount else 0 end) - sum(case when debit=1 then amount else 0 end) as available_balance
from `transaction`
where account_no=2549
The below query should work for you to get available balance.
select sum(amt) from
(select
case
when credit=1 then amount
when debit=1 then -amount
else 0
end as amt
from transaction
where account_no = 5294)t;

Query to get column totals and Subtract MySQL

I have a transaction table
I am able to get all the debit and credit transaction totals by property separately using these queries
SELECT property, SUM(amount) as creditamount FROM transactions WHERE transactions.type="CREDIT" GROUP BY property
SELECT property, SUM(amount) as debitamount FROM transactions WHERE transactions.type="DEBIT" GROUP BY property
I am facing difficulty in having these two queries done in a single query so that i can subtract credit amount and debit amount for each row and list it according to the property
I tried using sub queries but multiple rows are returned.
Any way to achieve this?
Conditional aggregation may be what you are looking for.
SELECT property,
SUM(case when type = 'Credit' then amount else 0 end) as creditamount,
SUM(case when type = 'Debit' then amount else 0 end) as debitamount,
SUM(case when type = 'Credit' then amount else 0 end) -
SUM(case when type = 'Debit' then amount else 0 end) as diff
FROM transactions
GROUP BY property
Use self join
select debitamount , creditamount
from (select sum(amount) income
from transactions
WHERE transactions.type="CREDIT"
GROUP BY property) i
JOIN (select sum(rate) debitamount
from transactions
WHERE transactions.type="DEBIT"
GROUP BY property) e
Refer this question

mysql table data output in a single row based on the type of the data

I have the following data in mysql table called wallet_txns.
wlt_name wlt_txn_type wlt_txn_amount
A Income 200
A Expense 100
B Income 100
B Income 500
B Expense 200
I trying to get the output of the data like below ( the sum of income and expense in a single row)
Wlt_name Expense Income
A 100 200
B 200 600
I have used the following query, But i am not getting the output as expected, (the income and expense in getting in seperate rows) Please help...
select
wlt_name,
if(wlt_txn_type = 'Expense', wlt_txn_amount, 0) as Expense,
if(wlt_txn_type = 'Income', wlt_txn_amount, 0) as Income
from wallet_txns
;
Maybe you can help this part of the code: SUM(IF(wlt_txn_type = "Income", wlt_txn_amount, 0)) AS IncomeTotal.
You already almost wrote correct query, but you forget about sum and group. Here query:
select
wlt_name,
sum(if(wlt_txn_type = 'Expense', wlt_txn_amount, 0)) as Expense,
sum(if(wlt_txn_type = 'Income', wlt_txn_amount, 0)) as Income
from wallet_txns
group by wlt_name
;
You can use conditional sum and then group by
select
wlt_name,
sum(
case when wlt_rxn_type ='Income' then wlt_txn_amount else 0 end
) as `Income`,
sum(
case when wlt_rxn_type ='Expense' then wlt_txn_amount else 0 end
) as `Expense`
from wallet_txns group by wlt_name;
You could do something like this:
SELECT
Wlt_name,
SUM(CASE WHEN wlt_txn_type='Expense' THEN wlt_txn_amount ELSE 0 END) AS Expense,
SUM(CASE WHEN wlt_txn_type='Income' THEN wlt_txn_amount ELSE 0 END) AS Income
FROM
wallet_txns
GROUP BY
Wlt_name
I'm not a mysql user, but TSQL has little secrets to me. Check for PIVOT - UNPIVOT alternatives on the WWW.

How to change the value of sum function inside the query?

I have a query with sum aggregation function :
SELECT sum(case when result=1 then 1 when result=2 then 0)as final_result From results
I want to change this part when result=2 then 0 to something like that when result=2 then final_result equals zero
Is it possible to do this ? or there is another way for that?
Try this :
SELECT CASE WHEN cnt=sum THEN sum ELSE 0 END as Final_result
FROM
(
SELECT count(*) as cnt,
SUM(case when result=1 then 1 else 0 end) as sum
from results
) Temp
Working Fiddle here.
Explanation:
Inner query select the total number of records and the sum of the records. Then if those count and sum are equal that means all values are 1.
NB: Removed the checking when result=2 then 0 because, the query will select 0 for any values other than 1. So there is no need to check for result=2.
EDIT:
To find the count of 10 consecutive 1's, you can do:
SELECT SUM(CASE WHEN RN=10 THEN 1 ELSE 0 END) AS final_result
FROM
(
SELECT CASE WHEN result=1 THEN #row_number:=#row_number+1 ELSE #row_number:=0 END AS RN,
result
FROM results, (SELECT #row_number:=0) AS t
) Temp
Sample Fiddle here.
I think you want something like this:
SELECT case max(case result when 2 then 1 else 0 end)
when 1 then 0
else sum(case when result=1 then 1 else 0 end)
end as final_result
From results
Fiddle here
So what I'm doing is checking for the final-result-must-be-0 condition inside a MAX(). That way, if any of the rows meets this condition (i.e. result = 2), the maximum value will be 1. Then I can use that value to determine whether I wanna return 0 or do the SUM().