简体   繁体   中英

SQL Case Expression with a Where Clause

I have the following example Data set that was created by the following query that sets an employee as "Active' or 'Inactive" based on if they worked any hours during a month.

Select  Concat([First Name],' ', [Last Name]) AS 'FullName',
CASE (SUM([Week 1] + [Week 2] + [Week 3] + [Week 4]))
        When 0 Then 'Inactive'
        ELSE 'Active'
END [Status]
From dbo.hours
Group by [first name], [last name]
FullName Status
Alan Brewer Active
Alejandro McGuel Inactive
Alex Nayberg Active

Im trying to get rid of all the 'Active' Status rows so that my query only displays those who are 'inactive'. I attempted to add WHERE Status = Inactive between the FROM and GROUP BY expression but it returns no results. (Does not give an error, just returns empty columns).

Anyone know what I am missing?

You can't add a WHERE condition on the Status column just like that since it's not available to WHERE clause.. you can use that query as inline view and do the condition check in outer query like

select * from (
Select  Concat([First Name],' ', [Last Name]) AS 'FullName',
CASE (SUM([Week 1] + [Week 2] + [Week 3] + [Week 4]))
        When 0 Then 'Inactive'
        ELSE 'Active'
END [Status]
From dbo.hours
Group by [first name], [last name] ) xxx
where Status != 'Active';

You need a HAVING clause, but also for your requirement you don't need the CASE expression:

SELECT  CONCAT([First Name],' ', [Last Name]) AS FullName,
        'Inactive' [Status]
FROM dbo.hours
GROUP BY [first name], [last name]
HAVING SUM([Week 1] + [Week 2] + [Week 3] + [Week 4]) = 0

CTE will work as well:

with cte as(
Select  Concat([First Name],' ', [Last Name]) AS 'FullName',
CASE (SUM([Week 1] + [Week 2] + [Week 3] + [Week 4]))
        When 0 Then 'Inactive'
        ELSE 'Active'
END [Status]
From dbo.hours
Group by [first name], [last name])
select FullName from cte where Status <> 'Active'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM