Subtracting Two Column With Null - sql

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

Related

how to combine these two queries in a single query

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

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

Sql ISNULL condition in Sql Pivot and Sql case

I searched for many solutions on SO and elsewhere but couldn't quite understand how to write a query for my problem.
Anyway my query looks like below
SELECT * FROM
(
SELECT Id, Date, Name, Amount,
CASE
WHEN DATEDIFF(DAY,Date,GETDATE()) <=0
THEN 'Current'
WHEN DATEDIFF(DAY,Date,GETDATE()) <30
THEN 'Due30'
WHEN DATEDIFF(DAY,Date,GETDATE()) <60
THEN 'Due60'
ELSE 'Due90'
END AS [Age]
FROM Statement
WHERE (Amount <> 0)
) AS S
PIVOT
(
SUM(Amount)
FOR[Age] IN ([Current],[Due30],[Due60],[Due90])
) P
and the result looks like this
Id Date Name Current Due30 Due60 Due90
----------- ---------- --------------------------------------------
1 2016-04-03 Alan NULL NULL NULL 110.00
2 2016-05-02 TC NULL NULL 30.00 NULL
where should i insert IsNull condition to be able to remove the null in the result and add a zero there.
I tried inserting IsNull in the pivot query but we all know that is not meant to work
You have to add it repetitively in the final SELECT, when you replace the SELECT * (which should only exist in ad-hoc queries or EXISTS tests) with the column list:
SELECT
Id,
Date,
Name,
COALESCE([Current],0) as [Current],
COALESCE(Due30,0) as Due30,
COALESCE(Due60,0) as Due60,
COALESCE(Due90,0) as Due90
FROM
(
SELECT Id, Date, Name, Amount,
CASE
WHEN DATEDIFF(DAY,Date,GETDATE()) <=0
THEN 'Current'
WHEN DATEDIFF(DAY,Date,GETDATE()) <30
THEN 'Due30'
WHEN DATEDIFF(DAY,Date,GETDATE()) <60
THEN 'Due60'
ELSE 'Due90'
END AS [Age]
FROM Statement
WHERE (Amount <> 0)
) AS S
PIVOT
(
SUM(Amount)
FOR[Age] IN ([Current],[Due30],[Due60],[Due90])
) P
I've also used COALESCE since it's generally the preferred option (ANSI standard, extends to more than two arguments, applies normal type precedence rules) instead of ISNULL.
SELECT Id
, [Date]
, Name
, [Current] = SUM(CASE WHEN val <= 0 THEN Amount ELSE 0 END)
, Due30 = SUM(CASE WHEN val < 30 THEN Amount ELSE 0 END)
, Due60 = SUM(CASE WHEN val < 60 THEN Amount ELSE 0 END)
, Due90 = SUM(CASE WHEN val >= 60 THEN Amount ELSE 0 END)
FROM dbo.[Statement] t
CROSS APPLY (
SELECT val = DATEDIFF(DAY, [Date], GETDATE())
) s
WHERE Amount <> 0
GROUP BY Id, [Date], Name

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

Update Value without cursor

I have a table in the database.
Bill
ID Total Paid Status
1 1000 1000 Paid
2 500 400 Part Paid
3 700 0 Unpaid
4 200 0 Unpaid
Now the User pays PAID_AMT -> $900, which i want to distribute such that my table looks:
ID Total Paid Status
1 1000 1000 Paid
2 500 500 Paid
3 700 700 Paid
4 200 100 Part Paid
It can be easily done using cursor, but i want to avoid cursors.
Is it possible to achieve this using simple update queries with Output parameters.
Something like this
Update Bill
Set Paid = Total,
Status = 'Paid',
Output PAID_AMT = PAID_AMT - (Total-Paid )
where Total-Paid > PAID_AMT
The following query shows the amount owed, assuming SQL Server 2012:
select b.*,
sum(total - paid) over (order by id) as cumNotPaid
from bill b
You can now distribute the amount:
select b.*,
(case when cumNotPaid >= #AMOUNT then 0
when cumNotPaid - toBePaid <= #AMOUNT then toBePaid
else #AMOUNT - cumnotPaid
end) as PaidAmount
from (select b.*,
sum(total - paid) over (order by id) as cumNotPaid,
total - paid as ToBePaid
from bill b
) b
Now, this is an updatable CTE, so we can use this in an update statement:
with toupdate as (
(select b.*,
(case when cumNotPaid >= #AMOUNT then 0
when cumNotPaid - toBePaid <= #AMOUNT then toBePaid
else #AMOUNT - cumnotPaid
end) as PaidAmount
from (select b.*,
sum(total - paid) over (order by id) as cumNotPaid,
total - paid as ToBePaid
from bill b
) b
)
update toupdate
set paid = PaidAmount,
status = (case when total = paid then 'Paid' when total = 0 then 'UnPaid'
else 'PartPaid'
end);
I don't know what version of SQL server do you, if it 2008 then you could not use rolling sum with window function. You can try this recursive query:
declare #paid_amount int = 900
;with cte1 as (
select
b.id,
b.total - b.paid as diff,
row_number() over(order by id) as row_num
from Bill as b
where b.total <> b.paid
), cte2 as (
select
c1.id, c1.row_num, #paid_amount - c1.diff as paid_amount
from cte1 as c1
where c1.row_num = 1
union all
select
c1.id, c1.row_num, c2.paid_amount - c1.diff as paid_amount
from cte1 as c1
inner join cte2 as c2 on c2.row_num + 1 = c1.row_num
where c2.paid_amount > 0
)
update Bill set
Paid =
case
when c.paid_amount >= 0 then b.Total
else b.Total - b.Paid + c.paid_amount
end,
Status = case when c.paid_amount >= 0 then 'Paid' else 'Part Paid' end
from Bill as b
inner join cte2 as c on c.id = b.id
sql fiddle demo
for SQL server 2012 it's a bit easier:
declare #paid_amount int = 900
;with cte1 as (
select
b.id,
b.total - b.paid as amount_to_pay,
sum(b.total - b.paid) over(order by b.id) as amount
from Bill as b
where b.total <> b.paid
), cte2 as (
select
c.id,
#paid_amount - c.amount as remain_amount
from cte1 as c
where #paid_amount - c.amount + c.amount_to_pay >= 0
)
update Bill set
Paid =
case
when c.remain_amount >= 0 then b.Total
else b.Total - b.Paid + c.remain_amount
end,
Status = case when c.remain_amount >= 0 then 'Paid' else 'Part Paid' end
from Bill as b
inner join cte2 as c on c.id = b.id;
sql fiddle demo
If you are using SQL 2012 you can use the following:
DECLARE #PayAmount INT = 900;
WITH Dues AS
(
SELECT *, Total-Paid AS Due
FROM Bill
)
, Cumulative AS
(
SELECT *, SUM(Due) OVER (ORDER BY Id) AS CumulativeTotalDue
FROM Dues
)
, Payable AS
(
SELECT *, #PayAmount - CumulativeTotalDue AS AmountLeftAfterPaying
FROM Cumulative
)
, BillWithAmountToApplyRaw AS
(
SELECT *
, CASE
WHEN AmountLeftAfterPaying >= 0 THEN Due
ELSE Due + AmountLeftAfterPaying
END AS RawAmountToApply
FROM Payable
)
, BillWithAmountToApply AS
(
SELECT *, CASE WHEN RawAmountToApply < 0 THEN 0 ELSE RawAmountToApply END AS AmountToApply
FROM BillWithAmountToApplyRaw
)
That will give you the amount to apply in the AmountToApply column.
So you can use the above as
UPDATE BillWithAmountToApply
SET Paid = Paid + AmountToApply
FROM BillWithAmountToApply
(Use
SELECT *
FROM BillWithAmountToApply
to check it out first if you want)
SQL 2008 Version (less efficient because of the repeated joins, which aren't necessary in 2012):
WITH Dues AS
(
SELECT *, Total-Paid AS Due
FROM Bill
)
, CumulativeDue AS
(
SELECT base.Id, SUM(cumulative.Due) AS CumulativeTotalDue
FROM Dues base
JOIN Dues cumulative ON cumulative.Id <= base.Id
GROUP BY base.Id
)
, Cumulative AS
(
SELECT Dues.*, CumulativeDue.CumulativeTotalDue
FROM Dues
JOIN CumulativeDue ON CumulativeDue.Id = Dues.Id
)
... as above
Schema objects:
--BEGIN TRAN;
--CREATE TABLE Bill
--(
-- ID Int PRIMARY KEY IDENTITY,
-- Total INT NOT NULL,
-- Paid INT NOT NULL DEFAULT(0),
-- Status AS
-- CASE
-- WHEN Paid = Total THEN 'Paid'
-- WHEN Paid = 0 THEN 'Unpaid'
-- ELSE 'Part Paid'
-- END
--);
--WITH KnownValues(Total, Paid) AS
--(
-- SELECT 1000, 1000
-- UNION ALL SELECT 500, 400
-- UNION ALL SELECT 700, 0
-- UNION ALL SELECT 200, 0
--)
--INSERT INTO Bill(Total, Paid)
--SELECT *
--FROM KnownValues;
--COMMIT