Count Case with 2 columns with the same values (Clarified) - sql-server

Basically I want COUNT a CASE when values are present in 2 columns.
For example:
SELECT
COUNT
(CASE WHEN 1.sample AND 2.sample IN ('a','b','c')
THEN 1
ELSE NULL
END
) AS CASE
FROM table1 AS 1
INNER JOIN table2 AS 2
...
Message:
Conversion failed when converting the varchar value '08:12.06' to data
type int. Warning: Null value is eliminated by an aggregate or other
SET operation.
I get what's triggering the error, I just don't know a solution to count the case when values are present in both columns.

Can you try this and see if it works? I think this is what you are looking for.
SELECT
SUM
(CASE WHEN 1.sample IN ('a','b','c') AND 2.sample IN ('a','b','c')
THEN 1
ELSE 0
END
) AS CASE
FROM table1 AS 1
INNER JOIN table2 AS 2

You need to list the columns separately for comparison. Usually I specify a column to count, and you do not need to put NULL for the else condition.
SELECT
COUNT
(CASE WHEN 1.sample IS NULL OR 2.sample IS NULL THEN 0
WHEN ( 1.sample IN ('a','b','c')
AND 2.sample IN ('a','b','c')
)
THEN 1.sample
END
) AS CASE
FROM table1 AS 1
INNER JOIN table2 AS 2 ON....

Related

SQL Server case when date is null then select first then do another condition

I have a query where I am trying to do some conditions, but I always fail one out of the 3.
1st look if dischargedate is null then set order to 1, if dischargedate is not null then look into Rank column and pick the lowest rank and order by it. Query Below
For ClientId 3634164 I have 4 entries and works(picks the lowest rank as 1 as order of sort )
For ClientId 3634514 sees I have a dischargedate as null and that is our 1 order of sort
Where I fail is on ClientID 3634795, I have a dischargedate null but still picks the lowest rank as 1. How can I make it so that it picks the dischargedate as order of sort for that one?
The issue is with my sort only on ROW_NUMBER. In photo 1 and 2 pass but 3 the sort order 3 should be 1 Query
WITH CTE AS (
SELECT PC.OP__DOCID AS LegacyClientProgramId,
PC.ClientKey AS ClientId,
PC.PgmKey AS ProgramId,
CASE WHEN Date_Discharged_Program IS NULL THEN 4 ELSE 5 END AS STATUS,
PC.Date_Admit_Program AS RequestedDate,
PC.Date_Admit_Program AS EnrolledDate,
PC.Date_Discharged_Program AS DischargedDate,
TX.RANK,
ROW_NUMBER() OVER(PARTITION BY PC.ClientKey ORDER BY case when PC.Date_Discharged_Program
IS NULL THEN 0
when TX.Rank IS NOT NULL THEN 0
ELSE 1 END, TX.Rank) AS sortOrder
FROM FD__PROGRAM_CLIENT PC
LEFT JOIN LT__TXPLANHIERARCHY TX ON PC.PgmKey = TX.PgmKey
WHERE pc.ClientKey in ( SELECT ClientKey FROM LT__MIGRATE_CLIENT)
) SELECT LegacyClientProgramId,
ClientId,
ProgramId,
STATUS,
RequestedDate,
EnrolledDate,
DischargedDate,
sortOrder,
RANK,
CASE WHEN sortOrder = 1 THEN 'Y' ELSE 'N' END AS PrimaryAssignment
FROM CTE
WHERE ProgramId <> 54
You are assigning 0 to two different cases in your ROW_NUMBER() OVER ORDER BY ...) logic. This is placing PC.Date_Discharged_Program IS NULL and TX.Rank IS NOT NULL records at an equal starting position, with only TX.Rank acting as a tiebreaker. Since multiple rows have Rank = 60, the winner (sortOrder 1) is arbitrarily chosen.
Try:
... ORDER BY case when PC.Date_Discharged_Program IS NULL THEN 0
when TX.Rank IS NOT NULL THEN 1
ELSE 2
END,
TX.Rank) AS sortOrder

SQL CASE WHEN - NULL values returning unwanted rows

I have two case statements running in the same select statement, but here is a simplified example:
SELECT t.Person,
CASE WHEN t.Order LIKE 'Test Order 1 CHRG' THEN (SUBSTRING(t.Order PATINDEX('%[0-9]%',ord.Name),1)) END AS 'Order1'
CASE WHEN t.Order LIKE 'Test Order 2 CHRG' THEN (SUBSTRING(t.Order PATINDEX('%[0-9]%',ord.Name),1)) END AS 'Order2'
The results that I am getting are:
Name Order1 Order2
======================================
Person A 4 NULL
Person A NULL 3
Person B 2 NULL
Person B NULL 3
Person C 1 NULL
Person C NULL 5
Is there a way to ignore NULL value that is being produced by the CASE statements and have the query return only one row for each t.Name? Like this:
Name Order1 Order2
======================================
Person A 4 3
Person B 2 3
Person C 1 5
Thanks in advance!
(Now that I'm not on a Teams call) You're effectively doing a pivot here, which means you need to add some aggregation to eliminate the NULL values so that both values are on the same row. Filling in a few gaps, I suspect you therefore need:
SELECT t.Person,
MAX(CASE WHEN t.Order = 'Test Order 1 CHRG' THEN (SUBSTRING(t.Order PATINDEX('%[0-9]%',ord.Name),1)) END) AS Order1 --Don't use single quotes for aliases
MAX(CASE WHEN t.Order = 'Test Order 2 CHRG' THEN (SUBSTRING(t.Order PATINDEX('%[0-9]%',ord.Name),1)) END) AS Order2 --You didn't need LIKE either, as there was no pattern
FROM dbo.Table1 t
JOIN table2 ord ON t.id = ord.tid
GROUP BY t.Person;
Using Searched Case Statement is the best fit to exclude NULL marker from the result set of the Case Statement.
Below is the base T-SQL syntax for it;
--Searched CASE expression:
CASE
WHEN Boolean_expression THEN result_expression [ ...n ]
[ ELSE else_result_expression ]
END
Detailed information

Ignore condition in WHERE clause when column is NULL

I do have table were one row (with Type =E) is related to another row.
I have written query to return COUNT of those related rows. The problem is that there is no explicit relationship (like ID column that would clearly say which row is related to other row). Therefore I am trying to find relationship based on multiple conditions in WHERE clause.
The problem is that in few cases, the columns A and B could be NULL (for records where TYPE = 'M'). In such a cases I would like to ignore that condition, so It would use only first 3 conditions to determine relationship.
I have tried CASE Statement but is not working as expected:
SELECT [T1].[ID],[T1].[AlphaId],[T1].[Type],[T1].[A],[T1].[B],[T1].[Date],[T1].[ServiceID]
,( SELECT COUNT(*)
FROM MyTable T2
WHERE [T1].[AlphaId]=[T2].[AlphaId] AND
[T1].[Date]=[T2].[Date] AND
[T1].[ServiceID]=[T2].[ServiceID] AND
[T2].[A]=CASE WHEN [T2].[A] IS NULL THEN NULL ELSE [T1].[A] END AND
[T2].[B]=CASE WHEN [T2].[B] IS NULL THEN NULL ELSE [T1].[B] END AND
[T2].[Type]='M'
) as TotalCount
FROM MyTable T1
WHERE [T1].[Type] = 'E'
I can't ignore that condition, as for some cases the Date, ServiceID could be same, however it's the A, B which differs them. Luckily where A, B IS NULL, it is the Date, ServiceID which differs those two records.
http://sqlfiddle.com/#!3/c98db/1
Many thanks in advance.
You could join the tables and use COUNT and GROUP BY to get the counts. Then you can JOIN [A] and [B] if they are equal or NULL.
SELECT [T1].[ID],[T1].[AlphaId],[T1].[Type],[T1].[A],[T1].[B],[T1].[Date],[T1].[ServiceID], count([T2].[ID])
FROM MyTable T1
INNER JOIN MyTable T2 ON [T1].[AlphaId]=[T2].[AlphaId] AND
[T1].[Date]=[T2].[Date] AND
[T1].[ServiceID]=[T2].[ServiceID] AND
([T2].[A]= [T1].[A] OR [T2].[A] IS NULL )AND
([T2].[B]= [T1].[B] OR [T2].[B] IS NULL )AND
[T2].[Type] <> [T1].[Type]
WHERE [T1].[Type] = 'E'
GROUP BY [T1].[ID],[T1].[AlphaId],[T1].[Type],[T1].[A],[T1].[B],[T1].[Date],[T1].[ServiceID]

Handling TOP in A CASE-WHEN-THEN select

I am having a problem to resolve a SELECT CASE using TOP.
Should I mention I'm quite new to this ? :D
Also this is my first post on Stackoverflow. Hi !
I want to fill one column of informations from two tables :
Table 1 : Column 1 contains data I want to use
Table 1 : Column 2 is a join
Table 2 : Column 1 contains data I want to use
Table 2 : Column 2 is a join
So :
Table 1 Column 1 contains letters (D M and T) and empty spaces.
Table 2 Column 1 contains words ('Rolls' 'Transfers' 'Delivery')
I'm trying to fill my column using the following conditions :
When column T1.C1 contains D, M or T, write D M or T.
When column T1.C1 is empty, look at column T2.C1 :
If column T1.C1 contains 'Rolls', write 'R'
Else don't write anything
Things get ugly really fast for me because the info I want from column B requires a TOP to be used.
THe best I could get so far is Incorrect syntax near the keyword 'From'.
Here is my code so far.
Any suggestions ?
SELECT
(CASE T1.C1
WHEN 'D'
THEN 'D'
WHEN 'M'
THEN 'M'
WHEN 'T'
THEN 'T'
WHEN (SELECT TOP 1 T2.C1 FROM T2 WHERE T1.C2=T2.C2)
THEN 'R'
ELSE
''
END) as my_data,
FROM T1
I think you should try to find a simpler way to write this, something along the lines of:
WITH cte
AS ( SELECT C1 ,
C2 ,
ROW_NUMBER() OVER ( PARTITION BY C2 ORDER BY col ) rn
FROM Table2
)
SELECT CASE WHEN T1.C1 = '' THEN LEFT(T2.C1, 1)
ELSE T1.C1
END AS my_data
FROM Table1 T1
LEFT OUTER JOIN cte T2 ON T1.C2 = T2.C2
AND T2.rn = 1
You haven't posted your table schema, so this may need to be adjusted.

Aggregate Function Error on an Expression

What could be wrong with this query:
SELECT
SUM(CASE
WHEN (SELECT TOP 1 ISNULL(StartDate,'01-01-1900')
FROM TestingTable
ORDER BY StartDate Asc) <> '01-01-1900' THEN 1 ELSE 0 END) AS Testingvalue.
The get the error:
Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
As koppinjo stated what your current (broken) query is doing is checking if you have a NULL-value (or StartDate = '01-01-1900') in your table, return either a 1 or a 0 depending on which, and then attempting to SUM that single value.
There are 2 different logical things you want.
Either getting the amount of rows that has a StartDate or checking if any row is missing StartDate.
SELECT --Checking if there is a NULL-value in table
(
CASE WHEN
(SELECT TOP 1 ISNULL(StartDate,'01-01-1900')
FROM TestingTable
ORDER BY StartDate Asc) <> '01-01-1900' THEN 1
ELSE 0
END
) AS TestingValue
SELECT SUM(TestingValue) TestingValue --Give the count of how many non-NULLs there is
FROM
(
SELECT
CASE WHEN
ISNULL(StartDate,'01-01-1900') <> '01-01-1900' THEN 1
ELSE 0
END AS TestingValue
FROM TestingTable
) T
Here is a SQL Fiddle showing both outputs side by side.
Hard to say, but you probably want something like this:
SELECT
SUM(TestingValue)
FROM
(SELECT
CASE
WHEN ISNULL(StartDate,'01-01-1900') <> '01-01-1900'
THEN 1
ELSE 0
END AS TestingValue
FROM TestingTable) t
As your original query is written now, your subquery will return 1 value overall, so your sum would be 1 or 0 always, not to mention it is illegal. To get around that, this SQL will apply the case statement to every row in the TestingTable and insert the result into a derived table (t), then the 'outer' select will sum the results. Hope this helps!

Resources