如何对查询应用Where或Having子句?我遇到了Having子句的问题。
DECLARE @dtDate DATE
SET @dtDate = GETDATE();
with EMS as
(
select * from ReportingView.WTA where FiscalMonth = DATENAME(MONTH, @dtDate) + ', ' + DATENAME(YEAR, @dtDate) and ProductGroup = 'AAD'
)
select
[ID]
,(CASE
WHEN Entitlements <= 0 THEN '0'
ELSE CAST([Activations] as float) / [Entitlements]
END) as Utilization
from EMS
**HAVING Utilization >= .25**
答案 0 :(得分:1)
只有在使用GROUP BY时才会使用HAVING关键字。你想要的是一个WHERE,但除非你把它包装在子选择中,否则你将无法引用Utilization。
答案 1 :(得分:0)
where
和having
子句都在查询结尾处。如果您同时拥有两者,则where
会出现在having
。
在您的情况下,having
无效,因为having
只能与group by
一起使用。 having
基本上是汇总值的where
条款(例如sum
,count
等)
<强>示例:强>
<强> WHERE
强>
SELECT
*
FROM
EMS
WHERE
Utilization >= 0.25
<强> HAVING
强>
SELECT
col1, count(*)
FROM
EMS
GROUP BY
col1
HAVING
count(*) > 10
HAVING
和 WHERE
SELECT
col1, count(*)
FROM
EMS
WHERE
Utilization >= 0.25
GROUP BY
col1
HAVING
count(*) > 10
修改:此修改后的查询应该适合您。我不确定原始查询为何使用CTE,但我已将case
逻辑移至CTE。
with EMS as
(
select
[ID],
(
CASE
WHEN Entitlements <= 0 THEN '0'
ELSE CAST([Activations] as float) / [Entitlements]
END
) as Utilization
from
ReportingView.WTA
where
FiscalMonth = DATENAME(MONTH, @dtDate) + ', ' + DATENAME(YEAR, @dtDate)
and ProductGroup = 'AAD'
)
select
*
from
EMS
where
Utilizaiton >= .25