how to combine these two queries in a single query - sql

How to combine these two queries into single query
1. select sum(amount) as received from voucher where amount>0
2. select sum(amount) as repaid from voucher where amount<0

You may use conditional aggregation
select sum( case when amount > 0 then amount else 0 end ) as received,
sum( case when amount < 0 then amount else 0 end ) as repaid
FROM t
You may use FILTER in Postgres 9.4 +
select sum( amount ) filter (where amount > 0 ) as received,
sum( amount ) filter (where amount < 0 ) as repaid
FROM t

Try this.,
select case when amount>0 then sum(amount) end as 'received',
case when amount<0 then sum(amount) end as 'repaid' from voucher

Related

Using a case column within another case in select clause

I have a select clause with a case statement and I need to create another case statement comparing the column created by the previous case statement. Something like this:
select client
,discount
,(case when sales_avg>10000 then 30
when sales_avg>5000 then 20
else 0 end) discount_rule
,(case when discount < discount_rule then 1 else 0 end) status
from sales;
I get a message that discount_rule is unknown. How can I accomplish that?
You can use a Common Table Expression (CTE) and reference a CTE within a CTE as:
with CTE_discount_rule as
(
select client,
discount,
(case when sales_avg>10000 then 30
when sales_avg>5000 then 20
else 0 end) as discount_rule
from sales
),
CTE_Final_Status as
(
select client,
discount,
discount_rule,
(case when discount < discount_rule then 1 else 0 end) as status
from CTE_discount_rule
)
select * from CTE_Final_Status;
The simplest way is to use a subquery that returns the column discount_rule:
select t.client, t.discount, t.discount_rule,
case
when discount < discount_rule then 1
else 0
end status
from (
select client, discount,
case
when sales_avg > 10000 then 30
when sales_avg > 5000 then 20
else 0
end discount_rule
from sales
) t

Exclude lines within t_sql

I have a table
I need to exclude all lines where having round( sum(QtyInvoiced),1) = 0 and round(sum(Amount),1) =0
I try the following script but it dosen't work, how to correct it?
select sum( QtyInvoiced ) , sum(Amount) ,salesNumber
from invoicesales
group by salesNumber
except
select sum( QtyInvoiced ) , sum(Amount) ,salesNumber
from invoicesales
group by salesNumber
having round( sum(QtyInvoiced),1) = 0 and round(sum(Amount),1) =0
try like below using <> not equal
select sum( QtyInvoiced ) , sum(Amount) ,salesNumber
from invoicesales
group by salesNumber
having round( sum(QtyInvoiced),1) <> 0 and round(sum(Amount),1)<>0
If you want to exclude those rows, perhaps you want a NOT?
HAVING NOT(ROUND( SUM(QtyInvoiced),1) = 0 AND ROUND(SUM(Amount),1) = 0);
Otherwise yes, your SQL will do exactly what you've asked for to return the rows where the sum of QtyInvoiced and Amount equals 0 (not exclude those that do).

Simplify multiple subquery

I have a table with name loan_emi. I want select last emi payment date, last emi date, total no. of emi, no. of paid emi and no. of unpaid emi. here is my query.
SELECT MAX(emi_date)AS pay_date,
(SELECT MAX(emi_date) FROM loan_emi WHERE l_id=a.l_id AND is_paid=0
)AS last_date,
(SELECT COUNT(id) FROM loan_emi WHERE l_id=a.l_id
)AS tenor,
(SELECT COUNT(id) FROM loan_emi WHERE l_id=a.l_id AND is_paid=1
)AS paid,
(SELECT COUNT(id) FROM loan_emi WHERE l_id=a.l_id AND is_paid=0
)AS unpaid
FROM loan_emi a
WHERE id =" + lId + "
AND is_paid=1 GROUP BY l_id
But here is multiple sub queries. Please help me to simplify that. Thanks in advance.
just put into a single query with a case/when for each field. This way it is one pass for all the records for the ID in question, no joins, no subqueries. Also, as I have it, you probably want to PARAMETERIZE your query where indicated for the ID of the account in question...
SELECT
MAX( case when is_paid = 1 then emi_date else null end ) as Pay_Date,
MAX( case when is_paid = 0 then emi_date else null end ) as Last_Date,
COUNT(*) as Tenor,
SUM( case when is_paid = 1 then 1 else 0 end ) as Paid,
SUM( case when is_paid = 0 then 1 else 0 end ) as Unpaid
from
loan_emi
where
id = ?ParameterizeYourIncomingID
group by
l_id

how can i set the alias of column`s sum value based on another column in same table in sql?

I have a table of Accounts, having columns:
Acc_Id, Transaction_TypeId, Amount
I want to get result as When Transaction_TypeId = 1 then Sum of Amount as 'Total Advance Payments'.
Else when Transaction_typeId = 2 then Sum of Amount as 'Total Reciepts'
Here is my SQL query:
SELECT SUM(Amount) AS 'Sum' , Transaction_TypeId INTO #temp1 FROM AccountDetailTable WHERE Account_MasterId = 1 GROUP BY Transaction_TypeId
SELECT Sum as 'Total Advance' from #temp1 WHERE #temp1.Transaction_TypeId = 1;
SELECT Sum as 'Total Cash Receipts' FROM #temp1 WHERE #temp1.Transaction_TypeId = 2;
DROP TABLE #temp1;
but this query returns me two different result sets. How can i get the values in same result sets?
Use a CASE expression:
SELECT SUM(CASE WHEN Transaction_TypeId = 1 THEN somecolumn END) as [Total Advance],
SUM(CASE WHEN Transaction_TypeId = 2 THEN somecolumn END) as [Total Cash Receipts]
FROM #temp1;
You should use CASE EXPRESSION like this:
SELECT
sum(case when #temp1.Transaction_TypeId = 1 then amount else 0 end) as 'Total Advance',
sum(case when #temp1.Transaction_TypeId = 2 then amount else 0 end) as 'Total Cash Receipts'
FROM #temp1

Subtracting Two Column With Null

I use the following
select TotalCredits - TotalDebits as Difference
from
(
select
(select sum(TOTALAMOUNT) from journal where memberid=48 and CREDIT =1) as TotalCredits,
(select SUM(totalamount) from Journal where MEMBERID=48 and DEBIT =1) As TotalDebits
) temp
this returns one field with my difference, the problem i am occuring is that if the table has no credit, but has debits, the temp table contains a NULL value in the TotalCredits Field which prohibts math being done. (Vica Versa on has Credits but no Debits) I have tried coalese but cant seem how to make it work.
rationally i need to check if:
sum(TOTALAMOUNT) from journal where memberid=48 and CREDIT =1 as TotalCredits is
null then totalcredits = 0 and visa versa
sql server 2008
select ISNULL(TotalCredits,0) - ISNULL(TotalDebits,0) as Difference
from
(
select
(select sum(TOTALAMOUNT) from journal where memberid=48 and CREDIT =1) as TotalCredits,
(select SUM(totalamount) from Journal where MEMBERID=48 and DEBIT =1) As TotalDebits
) temp
Change your query to conditional aggregation and it fixes the problem:
select sum(case when credit = 1 then TotalAmount else -TotalAmount end) as Difference
from Journal
where memberid = 48 and (credit = 1 or debit = 1);
EDIT:
If you have the case where credit and debit could both be 1, then use:
select (sum(case when credit = 1 then TotalAmount else 0 end) -
sum(case when debit = 1 then TotalAmount else 0 end)
) as Difference
from Journal
where memberid = 48 and (credit = 1 or debit = 1);
Hello may be this can also can give the expected result
select COALESCE(TotalCredits,0) - COALESCE(TotalDebits,0) as Difference
from
(
select
(select sum(TOTALAMOUNT) from journal where memberid=48 and CREDIT =1) as TotalCredits,
(select SUM(totalamount) from Journal where MEMBERID=48 and DEBIT =1) As TotalDebits
) temp
Create a sub query using isnull to replace the null with 0 and then make the sum querys and then the total substraction
Ouch. That query makes my head hurt. Discriminant functions are your friend and case lets you create them easily in SQL. Just state the problem simply.
select total_credits = sum( case j.credit when 1 then 1 else 0 end ) ,
total_debits = sum( case j.debit when 1 then 1 else 0 end ) ,
total_delta = sum( case j.credit when 1 then 1 else 0 end )
- sum( case j.debit when 1 then 1 else 0 end )
from journal j
where j.memberid = 48