带有Where / Having子句的SQL查询案例

时间:2017-12-20 21:58:01

标签: mysql sql

如何对查询应用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**

2 个答案:

答案 0 :(得分:1)

只有在使用GROUP BY时才会使用HAVING关键字。你想要的是一个WHERE,但除非你把它包装在子选择中,否则你将无法引用Utilization。

答案 1 :(得分:0)

wherehaving子句都在查询结尾处。如果您同时拥有两者,则where会出现在having

之前

在您的情况下,having无效,因为having只能与group by一起使用。 having基本上是汇总值的where条款(例如sumcount等)

<强>示例:

<强> 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