SQL - Distinct with Case When - sql

When i use the following query it returns duplicate External IDs as it lists the different cases as different rows.
SELECT DISTINCT
OENT.OTHER_EXTERNAL_ID AS 'Agent Master Number'
,CASE WHEN SE.Organization_Name IS NULL OR RTRIM(LTRIM(SE.ORGANIZATION_NAME)) = '' THEN '' ELSE SE.ORGANIZATION_NAME END AS 'Agent'
GROUP BY
OENT.OTHER_EXTERNAL_ID
,CASE WHEN SE.Organization_Name IS NULL OR RTRIM(LTRIM(SE.ORGANIZATION_NAME)) = '' THEN '' ELSE SE.ORGANIZATION_NAME END
Where do i use the distinct properly so it lists the case as one row no matter what case it satisfies?
Thanks
Problem is that it keep returning
AGENT_NUMBER AGENT
MA12348677 DREHWING, DOUGLAS
MA12348677 DREHWING, DOUGLAS A
Where i want this to be one row as they have the same AGENT_NUMBER

select distinct
OENT.OTHER_EXTERNAL_ID AS AGENT_NUMBER,
CASE
WHEN SE.Organization_Name IS NULL OR RTRIM(LTRIM(SE.ORGANIZATION_NAME)) = '' THEN ''
ELSE upper( SE.ORGANIZATION_NAME )
END AS AGENT
FROM SomeTableName
order by AGENT_NUMBER
It will still return duplicates in case if Agent number differs. If you want to find duplicated names then
select AGENT, count (AGENT_NUMBER) from (
select OENT.OTHER_EXTERNAL_ID AS AGENT_NUMBER,
CASE
WHEN SE.Organization_Name IS NULL OR RTRIM(LTRIM(SE.ORGANIZATION_NAME)) = '' THEN ''
ELSE upper( SE.ORGANIZATION_NAME )
END AS AGENT
FROM SomeTableName
)
group by AGENT
HAVING count (AGENT_NUMBER) >1
order by AGENT
To find duplicate names for same Agent number:
select AGENT_NUMBER, count (AGENT) from (
select OENT.OTHER_EXTERNAL_ID AS AGENT_NUMBER,
CASE
WHEN SE.Organization_Name IS NULL OR RTRIM(LTRIM(SE.ORGANIZATION_NAME)) = '' THEN ''
ELSE upper( SE.ORGANIZATION_NAME )
END AS AGENT
FROM SomeTableName
)
group by AGENT_NUMBER
HAVING count (AGENT) >1
order by AGENT_NUMBER

Related

Join 2 Queries and a Pivot in SQL

I have 2 queries that I want to join together. They come from the same table, but the organization and structure of columns is bad. Hence the need for a Pivot in Query 1, then join it to Query 2.
I do know that this needs to be done with a CTE, but my output either results in a blank query, or info in the wrong columns.
I'm using SSMS18. Thanks for the help.
Query 1
Select *, '' AS 'DNC', '' AS 'DNF', '' AS 'DNR' from
(Select
Opin,
Qty,
[TicketDate],
[TicketNumber],
[Cust],
[ProdID]
from [dbo].[obser]) AS ID
Pivot (
SUM([Qty])
For [Opin] IN ([ArvUnits],[DeliveryUnits])
) AS SingleOTRow
where
TicketDate between '2021-01-01' and '2021-03-15'
and ProdID like '%_LB%'
Query 2
select
IOA.Cust, IOA.TicketNumber, IOA.TicketDate, '' AS 'ProdID','' AS 'IOA QTY', '' AS 'Delivery Units', IOA.ProdID AS 'DNC',
case
When IOA.Qty >=1 Then '1'
else 'N'
end AS 'DNF',
CASE
when IOA.ProdID = '21' Then 'Full'
else 'Not a Valid DNC- Review'
END as 'DNR'
from [dbo].[obser] AS IOA
where
IOA.TicketDate between '2021-01-01' and '2021-03-15' and
IOA.Opin= 'DNS'
Sample Data
[Sample Data]

How to return 'blank' using Sum function in Sql, if Sum is resulting 0 in SQL

I am using Sql Server 2008. I am adding some column value using Sum function. Like the code below:
SELECT 'RCOAuthorizer LMS',
'' AS Consumer_Loan,
'' AS Auto_Loan,
'' AS Credit_Card,
SUM(CASE
WHEN sq2.loan_type = 'Loan Amendment' THEN sq2.user_count
ELSE ''
END ) AS Loan_Amendment,
SUM(CASE
WHEN sq2.loan_type = 'Pre-Payment' THEN sq2.user_count
ELSE ''
END ) AS Pre_Payment,
SUM(CASE
WHEN sq2.loan_type = 'Corporate Credit card' THEN sq2.user_count
ELSE ''
END ) AS Corporate_Credit_card,
'' AS Auto_Payment_Release,
'' AS Car_Mulkiya
FROM
( SELECT 'RCOAuthorizer' AS ws_name,
'Loan Amendment' AS loan_type,
COUNT (DISTINCT a.bpm_referenceno) AS user_count,
a.user_id AS user_id
FROM BM_LMS_DecisionHistoryGrid a
INNER JOIN
( SELECT m.bpm_referenceno
FROM BM_LMS_EXTTABLE m
WHERE m.request_type = 'Loan Amendment' ) sq1 ON a.bpm_referenceno = sq1.bpm_referenceno
WHERE workstep_name = 'RCOAuthorizer'
GROUP BY a.user_id
UNION SELECT 'RCOAuthorizer',
'Pre-Payment',
COUNT (DISTINCT a.bpm_referenceno), a.user_id
FROM BM_LMS_DecisionHistoryGrid a
INNER JOIN
( SELECT m.bpm_referenceno
FROM BM_LMS_EXTTABLE m
WHERE m.request_type = 'Pre-Payment' ) sq1 ON a.bpm_referenceno = sq1.bpm_referenceno
WHERE workstep_name = 'RCOAuthorizer'
GROUP BY a.user_id
UNION SELECT 'RCOAuthorizer',
'Corporate Credit card',
COUNT (DISTINCT a.bpm_referenceno), a.user_id
FROM BM_LMS_DecisionHistoryGrid a
INNER JOIN
( SELECT m.bpm_referenceno
FROM BM_LMS_EXTTABLE m
WHERE m.request_type = 'Corporate Credit card' ) sq1 ON a.bpm_referenceno = sq1.bpm_referenceno
WHERE workstep_name = 'RCOAuthorizer'
GROUP BY a.user_id ) sq2
GROUP BY sq2.ws_name
The above query will return Sum of all the numbers available in 'a' column. But in case, there is no record, then it will return '0' as result.
I require that if there is no record, it must show blank instead of showing '0'. How to handle the same.
To start, you don't need an ISNULL with a back value of 0 (the neutral for adding) inside a SUM aggregate, as the SUM already ignores NULL values. So SUM(ISNULL(Column, 0)) is equal to SUM(Column) (but different from ISNULL(SUM(Column), 0)!).
Seems that you want a VARCHAR result instead of a numeric one. You can solve this with a CASE.
Select
CASE WHEN Sum(a) = 0 THEN '' ELSE CONVERT(VARCHAR(100), Sum(a)) END
from
table;
If you don't want to repeat the SUM expression:
;WITH SumResult AS
(
Select CONVERT(VARCHAR(100), Sum(a)) AS SumTotal
from table
)
SELECT
CASE WHEN R.SumTotal = '0' THEN '' ELSE R.SumTotal END
FROM
SumResult AS R
Keep in mind that in these both cases, if there is no record to calculate the sum from, the result will be NULL.
EDIT: There is no point in adding '' inside your SUM, as it's converted to 0 to be able to sum. The solution is still the same as I posted before.
Change
SUM(CASE
WHEN sq2.loan_type = 'Pre-Payment' THEN sq2.user_count
ELSE ''
END ) AS Pre_Payment,
for
CASE
WHEN SUM(CASE WHEN sq2.loan_type = 'Pre-Payment' THEN sq2.user_count END) = 0 THEN ''
ELSE CONVERT(VARCHAR(100), SUM(CASE WHEN sq2.loan_type = 'Pre-Payment' THEN sq2.user_count)) END AS Pre_Payment,
Just try this ( use isnull again ):
Select isnull(Sum(isnull(a,0)),0) from table_;
I used table_ instead of table, because table is a reserved keyword.
SQL Fiddle Demo

How can I use CASE clause twice in SQL Query

I am trying to apply two conditions in one SQL Query.
(select DISTINCT (
CASE WHEN (
ABC.GemUserID = '99' )
OR ABC.GemUserID != '99'
THEN 'Yes'
ELSE 'No'
END)) AS AllWell
This gives me output as "Yes" where as the CASE is true only for 1 file like below :
Current Result:
99 , Yes
99 , Yes
99 , Yes
Expected Result:
99 , No
99 , No
99 , Yes
I am using the below query but the SQL Query Intellisence is identifying it as wrong.
Wrong Query:
(select DISTINCT (
CASE WHEN ( ABC.GEMUserID = '99' THEN 'Yes' else 'No'
CASE WHEN ( ABC.GEMUserID != '99' THEN 'No' else 'Yes'
END)) AS AllWell
After fixing the above Wrong Query:
(select DISTINCT
(CASE WHEN ABC.GemUserID = '99' THEN 'Yes' else 'No' END),
(CASE WHEN ABC.GemUserID != '99' THEN 'No' else 'Yes' END))
AS AllWell
But I am getting error:
Msg 116, Level 16, State 1, Line 17 Only one expression can be
specified in the select list when the subquery is not introduced with
EXISTS.
How to fix this?
select distinct is -- itself -- part of SQL syntax. The distinct is not a function. It should not be followed by parentheses. So, if I understand your question:
select DISTINCT
( CASE WHEN ABC.GEMUserID = '99' THEN 'Yes' else 'No' END),
( CASE WHEN ABC.GEMUserID <> '99' THEN 'No' else 'Yes' END) as AllWell
Do you plan on giving the first column a name?
select DISTINCT
CASE WHEN ABC.GEMUserID = '99' THEN 'Yes'
ELSE 'No' -- This is automatically When ABC.GEMUserID <> '99'
END AS AllWell
According to the error, your query is a subquery (probably behind IN?) in a larger SQL command. Therefore, it is not possible for such subquery to return more than one column.
So your first query, you've said:
CASE WHEN userID = 99 OR userID != 99
In other words:
CASE WHEN 1=1
This is why it returns yes for everything (not sure what the difference between your current and expected result should be considering that the userID is 99 for all rows).
For your erroneous query, seems you're returning that select in the middle of another select (since you alias it at the end). Due to that, you cannot return more than one column in your nested select. You do not need the second CASE statement, simply change your query to:
(select DISTINCT
CASE WHEN ABC.GemUserID = '99' THEN 'Yes' Else 'No' End) AS AllWell
Assuming that you hold the missing pieces to the query such as the FROM.

Multiple And Statements

I am trying to identify when a record has AtAboveBelowGradeLevel = 1 for both years. In other words, how would I do case the case statement below?
SELECT AcademicYear
,SchoolName
,Subject
,LastName
,firstname
,StudentBKID
,AtAboveBelowGradeLevelCount
,CASE
WHEN AtAboveBelowGradeLevelCount = 1
AND AcademicYear = '2015-2016'
AND AcademicYear = '2016-2017'
AND AtAboveBelowGradeLevelCount = 1
THEN 'TRUE'
ELSE 'NO'
END
FROM StudentAssessmentMart.dbo.vwMAPAssessmentInformation
WHERE AcademicYear IN (
'2015-2016'
,'2016-2017'
)
AND SchoolName LIKE 'alliance%'
AND subject IN ('math')
AND StudentBKID IN (
'473106'
,'420219'
)
AND CalendarPeriodName = 'spring'
GROUP BY AcademicYear
,SchoolName
,Subject
,LastName
,firstname
,StudentBKID
,AtAboveBelowGradeLevelCount
ORDER BY StudentBKID
,AcademicYear
this is a simplify version
SELECT
StudentBKID
,CASE
WHEN COUNT(CASE WHEN AtAboveBelowGradeLevelCount = 1 THEN 1 END) = 2
THEN 'TRUE'
ELSE 'NO'
END
FROM StudentAssessmentMart.dbo.vwMAPAssessmentInformation
WHERE AcademicYear IN ('2015-2016','2016-2017')
AND SchoolName LIKE 'alliance%'
AND subject IN ('math')
AND StudentBKID IN ('473106','420219')
AND CalendarPeriodName = 'spring'
GROUP BY StudentBKID
The Year is already filter on the WHERE, so you only need a conditional counting so see how many of those are AboveBelowGrade

Group By Operator Not Behaving as Expected

I have this query:
SELECT groupname,
Result = CASE
WHEN ( thd_requesttype_dca_oms_form IS NULL
OR thd_requesttype_dca_oms_form = '' ) THEN
thd_requesttypeidmform
ELSE thd_requesttype_dca_oms_form
END
FROM zendeskticketexport
WHERE (groupname = 'DC Maintenance')
AND thd_requesttype_dca_oms_form = 'attribute_update_requests__discontinue___obsolete_request'
GROUP BY groupname,
thd_requesttype_dca_oms_form,
thd_requesttypeidmform
ORDER BY groupname
The result I am receiving:
groupname Result
DC Maintenance attribute_update_requests__discontinue___obsolete_request
DC Maintenance attribute_update_requests__discontinue___obsolete_request
DC Maintenance attribute_update_requests__discontinue___obsolete_request
What's throwing me off is the result; I believe the group by operator should group identical records together, but something with the group by operator in conjuction with the case operator is causing these records not to group. In testing the two cases, I see the following query is returning 0 records:
select * from ZendeskTicketExport
where groupName = 'DC Maintenance' and thd_requesttypeidmform = 'attribute_update_requests__discontinue___obsolete_request'
In my mind this would indicate that all of the records should group together, since the case operator is only returning values for the thd_requesttype_dca_oms_form field. Thanks in advance.
You're grouping by a third column. SQL Server will create your groups, even if that column itself isn't in the SELECT.
Try this instead:
SELECT groupname,
CASE
WHEN (thd_requesttype_dca_oms_form IS NULL OR
thd_requesttype_dca_oms_form = '' ) THEN thd_requesttypeidmform
ELSE thd_requesttype_dca_oms_form
END
FROM zendeskticketexport
WHERE
groupname = 'DC Maintenance' AND
thd_requesttype_dca_oms_form = 'attribute_update_requests__discontinue___obsolete_request'
GROUP BY groupname,
thd_requesttype_dca_oms_form,
CASE
WHEN (thd_requesttype_dca_oms_form IS NULL OR
thd_requesttype_dca_oms_form = '' ) THEN thd_requesttypeidmform
ELSE thd_requesttype_dca_oms_form
END
ORDER BY groupname