[英]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.
我试图在 FROM 和 GROUP BY 表达式之间添加 WHERE Status = Inactive ,但它没有返回任何结果。 (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您不能像这样在
Status
列上添加WHERE
条件,因为它不适用于WHERE
子句。您可以将该查询用作内联视图并在外部查询中进行条件检查,例如
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:您需要一个
HAVING
子句,但也为了您的要求,您不需要CASE
表达式:
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: CTE 也可以:
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.