Conditional summed value - sql

I am trying to add a case expression in my query but it is inside of a select from statement. SQL Server returns multiple errors when I try to execute it.
UNION all
SELECT 'Min WA APR for Canada MPL Receivables' AS [Text], ISNULL([Value],0.0) AS [Value], 'percent' AS [ValueType], [Limit], CASE WHEN [Excess] > 0 THEN 0 ELSE ABS(ISNULL([Excess],0.0)) END AS [Excess]
FROM (
--SELECT [part1]/[part2] AS [Value], [Limit], ([part1] - [Limit]*[part2])/(49.00 - [Limit]) AS [Excess]
SELECT [part1]/[part2] AS [Value], [Limit], ([part1] - [Limit]*[part2])/100.0 AS [Excess]
FROM (
CASE isLPP WHEN 1 THEN
SELECT SUM(RateLPP * OutstandingPrincipal * FAEligibility)
ELSE
SELECT SUM(APR * OutstandingPrincipal * FAEligibility)
END AS [part1]
FROM [dfc_BorrowingBaseRecords] WITH (NOLOCK)
WHERE FAEligibility = 1
AND Region = 'Canada'
AND LoanType = 'MPL'
) first
, (
SELECT 44.90 AS [Limit], SUM(OutstandingPrincipal * FAEligibility) AS [part2]
FROM [dfc_BorrowingBaseRecords] WITH (NOLOCK)
WHERE FAEligibility = 1
AND Region = 'Canada'
AND LoanType = 'MPL'
) second
) third
I need to do one calculation if a flag is set and another if it is not.

I think the following is what you are looking for.
The key point is to use the case expression inside the sum to conditionally determine what value you are summing.
SELECT 'Min WA APR for Canada MPL Receivables' AS [Text], ISNULL([Value],0.0) AS [Value]
, 'percent' AS [ValueType], [Limit]
, CASE WHEN [Excess] > 0 THEN 0 ELSE ABS(ISNULL([Excess],0.0)) END AS [Excess]
FROM (
SELECT [part1]/[part2] AS [Value], [Limit], ([part1] - [Limit]*[part2])/100.0 AS [Excess]
FROM (
SELECT 44.90 AS [Limit]
, SUM(CASE isLPP WHEN 1 THEN RateLPP ELSE APR END * OutstandingPrincipal * FAEligibility) [part1]
, SUM(OutstandingPrincipal * FAEligibility) [part2]
FROM [dfc_BorrowingBaseRecords]
WHERE FAEligibility = 1
AND Region = 'Canada'
AND LoanType = 'MPL'
) X
) Y

Related

How to split data in SQL

I have the following code:
select
FeeEarnerID,
(
select
(select [name] from [User] AS u where u.userid=f.userid)
from
feeearner AS f
where
f.FeeEarnerID=aa.FeeEarnerID
) FeeEarner,
sum(aa.FEES) Fees,
sum(aa.DISB) Disbursements,
sum(aa.CREDITORS) Creditors
from
(
SELECT
FeeEarner.FeeEarnerID,
case when WIPTransaction.WIPTransactionTypeID IN (1,17,18,20,21,25) then WIPTransaction.Amount else 0 end 'FEES',
case when WIPTransaction.WIPTransactionTypeID IN (2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,26,27,28,29) then WIPTransaction.Amount else 0 end 'DISB',
case when WIPTransaction.WIPTransactionTypeID IN (24) then WIPTransaction.Amount else 0 end 'CREDITORS'
FROM
(
(
FeeEarner
JOIN
WIPTransaction ON FeeEarner.FeeEarnerID = WIPTransaction.FeeEarnerID
)
JOIN
WIPTransactionType ON WIPTransactionType.WIPTransactionTypeID = WIPTransaction.WIPTransactionTypeID
)
WHERE
(WIPTransaction.TransactionDate BETWEEN '2020-10-01' AND '2020-12-31')
)
AS aa
group by
FeeEarnerID
Used Table names: WIPtransaction, WIPtransactiontype, Feeearner
I want to display two more columns at the end of the output, namely: Invoiced and Uninvoiced.
The "Invoicenumber" field in the "WIPtransaction" database will be tested for this. If the "Invoicenumber" is NULL - the transaction amount will be added to a sum in the uninvoiced column and if "Invoicenumber" contains a number - the transaction amount will be added to a sum in the invoiced column.
What is the code that I would need to write and where would it be placed?
select
FeeEarnerID,
(
select
(select [name] from [User] AS u where u.userid=f.userid)
from
feeearner AS f
where
f.FeeEarnerID=aa.FeeEarnerID
) FeeEarner,
sum(aa.FEES) Fees,
sum(aa.DISB) Disbursements,
sum(aa.CREDITORS) Creditors,
----------
SUM( InvoicedAmount) AS InvoicedAmount,
SUM(UnInvoicedAmount) AS UnInvoicedAmount
----------
from
(
SELECT
FeeEarner.FeeEarnerID,
case when WIPTransaction.WIPTransactionTypeID IN (1,17,18,20,21,25) then WIPTransaction.Amount else 0 end 'FEES',
case when WIPTransaction.WIPTransactionTypeID IN (2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,26,27,28,29) then WIPTransaction.Amount else 0 end 'DISB',
case when WIPTransaction.WIPTransactionTypeID IN (24) then WIPTransaction.Amount else 0 end 'CREDITORS',
----------
CASE WHEN WIPTransaction.Invoicenumber IS NOT NULL THEN WIPTransaction.Amount END AS InvoicedAmount,
CASE WHEN WIPTransaction.Invoicenumber IS NULL THEN WIPTransaction.Amount END AS UnInvoicedAmount
----------
FROM
FeeEarner
JOIN
WIPTransaction ON FeeEarner.FeeEarnerID = WIPTransaction.FeeEarnerID
JOIN
WIPTransactionType ON WIPTransactionType.WIPTransactionTypeID = WIPTransaction.WIPTransactionTypeID
WHERE
WIPTransaction.TransactionDate BETWEEN '2020-10-01' AND '2020-12-31'
)
AS aa
group by
FeeEarnerID
You can remove your derived query and combine it all into one. The FeeEarner double sub-query can also be optimized:
select
FeeEarnerID,
(
select [name] from [User] AS u where u.userid=FeeEarner.userid
) FeeEarner,
sum(case when WIPTransaction.WIPTransactionTypeID IN (1,17,18,20,21,25) then WIPTransaction.Amount else 0 end) Fees,
sum(case when WIPTransaction.WIPTransactionTypeID IN (2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,26,27,28,29) then WIPTransaction.Amount else 0 end) Disbursements,
sum(case when WIPTransaction.WIPTransactionTypeID IN (24) then WIPTransaction.Amount else 0 end) Creditors,
SUM(CASE WHEN WIPTransaction.Invoicenumber IS NOT NULL THEN WIPTransaction.Amount END) AS InvoicedAmount,
SUM(CASE WHEN WIPTransaction.Invoicenumber IS NULL THEN WIPTransaction.Amount END) AS UnInvoicedAmount
FROM
FeeEarner
JOIN
WIPTransaction ON FeeEarner.FeeEarnerID = WIPTransaction.FeeEarnerID
JOIN
WIPTransactionType ON WIPTransactionType.WIPTransactionTypeID = WIPTransaction.WIPTransactionTypeID
WHERE
WIPTransaction.TransactionDate BETWEEN '2020-10-01' AND '2020-12-31'
group by
FeeEarnerID;

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

issues in Case and when Statement

I have a question about Case and when statements. I have a list of two transtypeid like 10 and 12.
I tried to take sale1 amount like if the transtypeid 11 has a sum amount !=0 means, I need to minus the amount with sum amount of transtypeid 10
I tried a lot but nothing worked.
I have these queries I tried
select
CT.CustomerCode, C.CustomerName,
sale1 = case
when (ct.TransTypeID = 11) and (sum(ct.OVAmount - ct.OVDiscount) != 0)
then sum(ct.OVAmount - ct.OVDiscount) - sum(ct.OVAmount - ct.OVDiscount)
else 0
end,
C.CountryCode, C.CityCode
from
CustomerTransactions CT
inner join
Customers C ON CT.CustomerCode = C.CustomerCode
where
ct.TransDate >= '2015-01-01'
and ct.TransDate <= '2015-12-31'
and ct.TransTypeID in (10, 11)
group by
ct.CustomerCode, c.CustomerName, c.CountryCode, c.CityCode
Try calculate sale1 with this SQL code:
CASE WHEN
SUM(CASE WHEN ct.TransTypeID = 11
THEN ct.OVAmount - ct.OVDiscount
ELSE 0 END) != 0
THEN
SUM(CASE WHEN ct.TransTypeID = 11
THEN ct.OVAmount - ct.OVDiscount
ELSE O END)
- SUM(CASE WHEN ct.TransTypeID = 10
THEN ct.OVAmount - ct.OVDiscount
ELSE 0 END)
ELSE 0 END
I'm not sure that I understand what you need. But I give it a try since you are in hurry.
Something like this, maybe?
select
CT1.CustomerCode, C.CustomerName,
sale1 =
case
when ( sum(ct1.OVAmount - ct1.OVDiscount) != 0 )
then sum( ct1.OVAmount - ct1.OVDiscount ) - sum( ct2.OVAmount - ct2.OVDiscount )
else
0
end,
C.CountryCode, C.CityCode
from
Customers c
Inner join CustomerTransactions CT1 ON ( CT1.CustomerCode = C.CustomerCode ) And ( ct1.TransTypeID = 11 )
Inner join CustomerTransactions CT2 ON ( CT2.CustomerCode = C.CustomerCode ) And ( ct2.TransTypeID = 10 )
where
( ct1.TransDate >= '2015-01-01' )
and ( ct1.TransDate < '2016-01-01' )
and ( ct2.TransDate >= '2015-01-01' )
and ( ct2.TransDate < '2016-01-01' )
group by
ct1.CustomerCode,c.CustomerName,c.CountryCode,c.CityCode
Using CTEs:
with
cte10 ( CustomerId, amount ) as (
select
customerId, sum( amount ) as amount
from
CustomerTransaction
where
( Type = 1 )
group by CustomerId
),
cte11 ( CustomerId, amount ) as (
select
customerId, sum( amount ) as amount
from
CustomerTransaction
where
( Type = 2 )
group by CustomerId
)
select
c.Id, c.Description,
sale1 =
case
when ( cte10.amount <> 0 )
then cte10.amount - cte11.amount
else
0
end
from
Customer c
Inner join cte10 on ( cte10.CustomerId = C.id )
inner join cte11 on ( cte11.Customerid = C.id )

SQL Error :Full-text predicates cannot appear in an aggregate expression

I am trying to execute the following query and getting a error.
but when i tried to use commented lines its work. but not working with contains function.
select
2015-min(c.Year)+1 as experiance
, sum (case when not c.JudgementID_FK is null then 1 else 0 end ) as reported_Judgements
, sum( case
when
(
Contains( c.Result , 'ACCEPT')
or
Contains( c.Result , 'ALLOW' )
or
contains (c.Result , 'Grant')
-- (
-- c.Result = 'Accepted' or c.Result = 'Allowed'
-- or c.Result='allowed' or c.Result='accepted'
-- or c.Result ='bail allowed(accepted)'
-- or c.Result = 'admitted'
-- or c.Result = 'Accepted.'
-- or c.Result = 'accepted.'
-- )
-- and
--cl.LawyerOf = 'Petitioner'
)
then 1 else 0 end) as win_cases
, sum (case when c.JudgementID_FK is null then 1 else 1 end ) as total_Cases
from CaseTLS c, CaseLawyer cl , Lawyer l
Where
c.CaseId = cl.CaseId
and cl.ComputerCode = l.ComputerCode
group by l.computercode
order by l.computercode
According to this documentation "CONTAINS is a predicate used in the WHERE clause" and you are trying to use it in the SELECT clause.
Try using PATINDEX instead:
select
2015-min(c.Year)+1 as experiance
, sum (case when not c.JudgementID_FK is null then 1 else 0 end ) as reported_Judgements
, sum( case
when
(
PATINDEX( '%ACCEPT%', UPPER(c.Result)) > 0
or
PATINDEX( '%ALLOW%', UPPER(c.Result)) > 0
or
PATINDEX( '%GRANT%', UPPER(c.Result)) > 0
)
then 1 else 0 end) as win_cases
, sum (case when c.JudgementID_FK is null then 1 else 1 end ) as total_Cases
from CaseTLS c, CaseLawyer cl , Lawyer l
Where
c.CaseId = cl.CaseId
and cl.ComputerCode = l.ComputerCode
group by l.computercode
order by l.computercode

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