Case Statement having no effect on output - sql

I am trying to get sums of donations based on the bank approval status and grouped by gift kind. However, it the script outputs RR and NR donations on separate lines (see below the script). It seems like the case statements aren't working at all.
select gift_kind,
case
when c.bank_approval_status = 'AP' then
sum(c.charge_amount) end approved,
case
when c.bank_approval_status in ('RR','NR') then
sum(c.charge_amount) end rejected,
case
when c.bank_approval_status = 'AR' then
sum(c.charge_amount)*-1 end refunded,
case
when c.bank_approval_status not in ('AR','AP','RR','NR') then
sum(c.charge_amount) end other_status
from charge_log c, transactions t
where c.account_id=t.account_id
and c.process_id= 'CHG - 02532'
and c.gift_date=t.gift_date
and c.gift_seq=t.gift_seq
and C.PLEDGE_NUMBER=t.pledge_number
and t.sts='A'
group by t.fund_type, t.gift_kind, c.bank_approval_status
order by gift_kind asc

I believe you are looking for this logic:
select gift_kind,
sum(case when c.bank_approval_status = 'AP' then c.charge_amount
end) as approved,
sum(case when c.bank_approval_status in ('RR', 'NR') then c.charge_amount
end) as rejected,
sum(case when c.bank_approval_status in ('AR') then c.charge_amount*-1
end) as refunded,
sum(case when c.bank_approval_status not in ('AR','AP','RR','NR') then c.charge_amount
end) other_status
from charge_log c join
transactions t
on c.account_id = t.account_id and
c.gift_date = t.gift_date and
c.gift_seq = t.gift_seq and
C.PLEDGE_NUMBER = t.pledge_number
where c.process_id = 'CHG - 02532' and t.sts = 'A'
group by t.fund_type, t.gift_kind
order by gift_kind asc
Notes:
Learn to use proper JOIN syntax. Never use commas in the FROM clause.
The JOIN conditions should all be in the ON clause, not the WHERE clause.
The CASE is an argument to the SUM().
Remove the bank_approval_status from the GROUP BY.
I don't know why fund_type is in the GROUP BY. You may have a reason for that so I left it.

You need to put the case clauses inside the sums, and add else 0 to make sure you don't get null as a result:
sum(case
when c.bank_approval_status = 'AP' then
c.charge_amount else 0 end) approved,
sum(case
when c.bank_approval_status in ('RR','NR') then
c.charge_amount else 0 end) rejected,
sum(case
when c.bank_approval_status = 'AR' then
-c.charge_amount else 0 end) refunded,
sum(case
when c.bank_approval_status not in ('AR','AP','RR','NR') then
c.charge_amount else 0 end) other_status
And your group by should rarely be on columns you use in aggregations (here bank_approval_status in the sum). Change to:
group by gift_kind
Depending on your scheme, other fields might need to be added to the group by clause but then it would make sense to also put them in the select and order by clauses.

Related

SQL Query to Combine rows

I have a query that currently prints out what I need but doesn't combine the rows that I need. For example, I need the first two rows with the meter name to be combined together and so on for the rest of the meter names.
This is currently what I have:
SELECT
--Displays Client Number
CASE
WHEN v.MID IS NULL THEN ''
ELSE v.ClientNumber
END AS 'Client Number',
--Displays MID Number
CASE
WHEN v.MID IS NULL THEN ''
ELSE v.MID
END AS MID,
--Displays Meter Name
CASE
WHEN v.MID IS NULL THEN ''
ELSE v.MeterName
END AS 'Meter Name',
/*
CASE
WHEN v.MID IS NULL THEN 0
ELSE SUM(v.MCF)
END AS MCF,
*/
--Displays January's MCF
CASE
WHEN v.AccountPeriod = '2018-01-01' THEN SUM(v.MCF)
ELSE 0
END AS January,
--Displays Febuary's MCF
CASE
WHEN v.AccountPeriod = '2018-02-01' THEN SUM(v.MCF)
ELSE 0
END AS Febuary,
CASE
WHEN v.MID IS NULL THEN 0
ELSE SUM(v.mcf)
END AS 'Meter Total'
FROM Volumes v
LEFT JOIN CurrentMeters cm
ON v.MID = cm.MID
WHERE cm.ClientNumber = 107500
GROUP BY v.MID, v.AccountPeriod, v.ClientNumber, v
Does anyone have any suggestions as to what I should do or how I should approach this?
I think you just want conditional aggregation:
SELECT (CASE WHEN v.MID IS NULL THEN '' ELSE v.ClientNumber END) AS Client_Number,
COALESCE(WHEN v.MID, '') as MID,
(CASE WHEN v.MID IS NULL THEN '' ELSE v.MeterName END) AS Meter_Name,
SUM((CASE WHEN v.MID IS NULL THEN 0 v.MCF END) AS MCF,
SUM(CASE WHEN v.AccountPeriod = '2018-01-01' THEN v.MCF ELSE 0 END) AS January,
SUM(CASE WHEN v.AccountPeriod = '2018-02-01' THEN v.MCF ELSE 0 END) AS January,
SUM(CASE WHEN v.MID IS NULL THEN 0 ELSE v.mcf END) AS Meter_Total
FROM Volumes v JOIN
CurrentMeters cm
ON v.MID = cm.MID
WHERE cm.ClientNumber = 107500
GROUP BY (CASE WHEN v.MID IS NULL THEN '' ELSE v.ClientNumber END),
COALESCE(WHEN v.MID, ''),
(CASE WHEN v.MID IS NULL THEN '' ELSE v.MeterName END);
Notes:
Your WHERE clause is turning the outer join into an inner join, so there is no reason to express an outer join.
The GROUP BY keys specify what defines a row in the result set. Each combination of unique values in the data is in exactly one row. Hence, you don't want AccountPeriod in the GROUP BY.
Presumably, you want one row for each of the expressions that define a row, so these expressions are in the group by.
For conditional aggregation, the CASE expression is an argument to an aggregation function such as SUM().

Trying to group several rows based on donatedmoney status

I'm really struggling with this. I just can't seem to figure it out. I've got the concept in my head but don't exactly know how to put my plain language understanding of how to solve the problem into the correct Syntax.
Here is the question.
Give me a list of all donors and their addresses categorized by whether they donated art, money, or both.
Here is the set up for the tables.
CareTakers: CareTakerID, CareTakerName
Donations: DonationID, DonorID, DonatedMoney, ArtName, ArtType, ArtAppraisedPrice, ArtLocationBuilding, ArtLocationRoom, CareTakerID
Donors: DonorID, DonorName, DonorAddress
Here is what I have for my code so far.
SELECT
DISTINCT(DonorName), DonorAddress
FROM
Donors JOIN Donations ON Donors.DonorID = Donations.DonorID
GROUP BY
DonatedMoney
HAVING
DonatedMoney = 'Y' OR DonatedMoney = 'N' OR DonatedMoney = 'Y' AND ArtName IS NOT NULL
Any help would be highly appreciated!
Why would you use a having clause? The question specifies no filtering. The following summarizes the donations to get what you need and then joins the results back to the donors table:
select d.*, don.DonationType
from donors d join
(select don.donorid,
(case when sum(case when donatedmoney = 'Y' then 1 else 0 end) > 0 and
sum(case when artname is not null then 1 else 0 end) > 0
then 'Both'
when sum(case when donatedmoney = 'Y' then 1 else 0 end) > 0
then 'Money'
when sum(case when artname is not null then 1 else 0 end)
then 'Art'
else 'Neither'
end) as DonationType
from donations don
group by don.donorid
) don
on d.donorid = don.donorid

How do you count misspelled fields using a SQL query?

I have a SQL database that I am querying as part of a project - I only have read access to it.
There is a column called ResultStatus - possible values are "Passed" and "Failed". However, there were some typos by the original data inputter so some of them say "Fialed" as well.
I want to count the number of "Failed" entries, but I want to include the "Fialed" ones as well.
SELECT
ResultStatus, Count(*)
FROM
[DB_018].[dbo].[ProjectData]
GROUP BY ResultStatus
is obviously grouping "Fialed" in a different category. I want it to be counted along with "Failed".
You can correct the spelling yourself
SELECT Case When ResultStatus = 'Fialed' then 'Failed' Else ResultStatus End AS ResultStatus, Count(*)
FROM [DB_018].[dbo].[ProjectData]
GROUP BY Case When ResultStatus = 'Fialed' then 'Failed' Else ResultStatus End
What this is doing is replacing the incorrect spelling with the correct one while you group the data.
Note that this is possible, and possibly cleaner, to do using a CTE
with CleanedResults as (
select
case
when ResultStatus = 'Fialed' then 'Failed'
when ResultStatus = 'Pased' then 'Passed'
else ResultStatus
end as ResultStatus
from [DB_018].[dbo].[ProjectData]
) select
ResultStatus
, count(*) as NumResults
from CleanedResults
group by ResultStatus
I'd use:
SELECT
case when left(ResultStatus,1) = 'P' then 'Pass'
when left(ResultStatus,1) = 'a' then 'audit'
else 'fail' end as result, Count(*)
FROM
ProjectData
GROUP BY left(ResultStatus,1)
as COUNT will not really count NULL values, then you can use CASE statement and just writes as below:
SELECT COUNT(CASE WHEN ResultStatus = 'Fialed' THEN 1
END) as MissSpelledFailed,
COUNT(CASE WHEN ResultStatus = 'Pased' THEN 1
END) as MisSpelledPassed,
COUNT(CASE WHEN ResultStatus = 'Failed' THEN 1
END) as CorrectSpelledFailed,
COUNT(CASE WHEN ResultStatus = 'Passed' THEN 1
END) as CorrectSpelledPassed,
FROM [DB_018].[dbo].[ProjectData]
You need to get a distinct list of ResultStatus and add them all to the case statement below. I prefer this method to Raj's as you don't need to use a CTE (not available in all version of SQL Server) or adjusting the group by.
SELECT
ResultStatus,count(*) [Count]
FROM(
SELECT
CASE
WHEN ResultStatus = 'FIAL' THEN 'FAIL'
WHEN ResultStatus = 'FAIL' THEN 'FAIL'
WHEN ResultStatus = 'Passed' THEN 'Passed'
END [ResultStatus]
FROM [DB_018].[dbo].[ProjectData]
)a
GROUP BY ResultStatus

Oracle SQL Count with join

I am trying to count Orders and Order lines dependent upon order type. So far i have counted the Order headers per order type.
SELECT lifnr,
COUNT(CASE WHEN e1.bsart = 'NB' THEN 1 ELSE NULL END) Schedule_Orders,
COUNT(CASE WHEN e1.bsart = 'ZNBS' THEN 1 ELSE NULL END) Store_Orders,
COUNT(CASE WHEN e1.bsart = 'ZCSO' THEN 1 ELSE NULL END) Third_Party,
COUNT(CASE WHEN e1.bsart NOT IN ('ZCSO', 'NB', 'ZNBS' ) THEN 1 ELSE NULL END) Other_Orders,
COUNT(*) Total_Orders
FROM saprpe.ekko e1
JOIN saprpe.ekpo p1
ON e1.ebeln = p1.ebeln
WHERE e1.aedat BETWEEN '20130701' AND '20140701'
GROUP BY lifnr
Order Lines are stored in table EKPO so i have joined EKKO to EKPO using the document number. How do i go about counting order lines for each of the order types on the case above? I've only managed to count ALL order lines, not specifically for each order type.
Extra Info: An Order header is stored in EKKO which contains a Vendor, an OrderNumber and an OrderType. EKKO has a 1-to-many relationship with table EKPO which contains Order lines. Order lines relates to Order Header through the Order Number.
What i am trying to do is get the total order headers for the three order types NB, ZNBS and ZCSO, and the total lines for each order type. All into their own columns
For example I would want to see;
Vendor1, 10 NB orders, 100 NB Order Lines, 0 ZNBS Orders, 0 ZNBS Order Lines, 5 ZCSO Orders, 15 ZCSO Order Lines, 15 Total Orders, 115 Total Order Lines
Please point out if i need to clarify anything. I should note i would prefer this in a single SQL query, i can manage it on an individual query basis for each Order Type using the WHERE clause.
After some trial and error, googling etc, I eventually got there.
SELECT
lifnr,
COUNT(DISTINCT (CASE WHEN e1.bsart = 'NB' THEN e1.ebeln ELSE NULL END)) Schedule_Orders,
COUNT(CASE WHEN e1.bsart = 'NB' THEN e1.ebeln ELSE NULL END) Schedule_Order_Lines,
COUNT(DISTINCT (CASE WHEN e1.bsart = 'ZNBS' THEN e1.ebeln ELSE NULL END)) Store_Orders,
COUNT(CASE WHEN e1.bsart = 'ZNBS' THEN e1.ebeln ELSE NULL END) Store_Order_Lines,
COUNT(DISTINCT (CASE WHEN e1.bsart = 'ZCSO' THEN e1.ebeln ELSE NULL END)) Third_Party,
COUNT(CASE WHEN e1.bsart = 'ZCSO' THEN e1.ebeln ELSE NULL END) Third_Party_Lines,
COUNT(DISTINCT (CASE WHEN e1.bsart NOT IN ('ZCSO', 'NB', 'ZNBS' ) THEN e1.ebeln ELSE NULL END)) Other_Orders,
COUNT(CASE WHEN e1.bsart NOT IN ('ZCSO', 'NB', 'ZNBS') THEN e1.ebeln ELSE NULL END) Other_Order_Lines,
COUNT(DISTINCT(e1.ebeln)) Total_Orders,
COUNT(e1.ebeln) Total_Order_Lines
FROM saprpe.ekko e1
LEFT JOIN saprpe.ekpo p1
ON e1.ebeln = p1.ebeln
WHERE e1.aedat BETWEEN '20130701' AND '20140701'
GROUP BY lifnr
The JOIN originally was making my header count the same count as the lines because of the relationship between the tables... Adding DISTINCT to my header counts and using a case for the line counts enabled me to count for those order types.

Merging data SQL Query

I have a query request where I have to show one customer activity for each web-site but it has to be only one row each, instead of one customer showing multiple times for each activity.
Following is the query I tried but brings lot more rows. please help me as how I can avoid duplicates and show only one customer by each row for each activity.
SELECT i.customer_id, i.SEGMENT AS Pistachio_segment,
(CASE when S.SUBSCRIPTION_TYPE = '5' then 'Y' else 'N' end ) PB_SUBS
(CASE WHEN S.SUBSCRIPTION_TYPE ='12' THEN 'Y' ELSE 'N' END) Daily_test,
(CASE when S.SUBSCRIPTION_TYPE ='8' then 'Y' else 'N' end) COOK_4_2
FROM IDEN_WITH_MAIL_ID i JOIN CUSTOMER_SUBSCRIPTION_FCT S
ON I.IDENTITY_ID = S.IDENTITY_ID and I.CUSTOMER_ID = S.CUSTOMER_ID
WHERE s.site_code ='PB' and s.subscription_end_date is null
Sounds like you need to group by customer_id and perform aggregations for the other columns you are selecting. For example:
sum(case when s.subscription_type = '5' then 1 else 0 end) as pb_subs_count
You could try one of two things:
Use a GROUP BY statement to combine all records with the same id, e.g.,
...
WHERE s.site_code ='PB' and s.subscription_end_date is null
GROUP BY i.customer_id
Use the DISTINCT command in your SELECT, e.g.,
SELECT DISTINCT i.customer_id, i.SEGMENT, ...
you could use a aggregation (SUM) on customer_id, but what do you expect to happen on the other fields? for example, if you have SUBSCRIPTION_TYPE 5 and 13 for the same customer (2 rows), which value do you want?
Perhaps you are looking for something like this:
SELECT i.customer_id, i.SEGMENT AS Pistachio_segment,
MAX(CASE when S.SUBSCRIPTION_TYPE = '5' then 'Y' else 'N' end ) PB_SUBS
MAX(CASE WHEN S.SUBSCRIPTION_TYPE ='12' THEN 'Y' ELSE 'N' END) Daily_test,
MAX(CASE when S.SUBSCRIPTION_TYPE ='8' then 'Y' else 'N' end) COOK_4_2
FROM IDEN_WITH_MAIL_ID i JOIN CUSTOMER_SUBSCRIPTION_FCT S
ON I.IDENTITY_ID = S.IDENTITY_ID and I.CUSTOMER_ID = S.CUSTOMER_ID
WHERE s.site_code ='PB' and s.subscription_end_date is null
GROUP BY i.customer_id, i.SEGMENT
I can't be sure, though, without knowing more about the tables involved.