Sql 错误:尝试筛选别名列名时列名无效

Sql 错误:尝试筛选别名列名时列名无效,sql,sql-server,tsql,Sql,Sql Server,Tsql,以下代码给出了此错误: 味精207,16级,状态1,第6行 无效的列名“AdvertisementSprint” 我需要应用广告sprint>0,如何调整我的代码 SELECT DATEPART(hh, DateCreated) AS Hour, AdvertisementId, COUNT(CASE WHEN IsPrinted = 1 THEN IsPrinted END) AS AdvertisementsPrinted FROM dbo.GaAnalyt

以下代码给出了此错误:

味精207,16级,状态1,第6行
无效的列名“AdvertisementSprint”

我需要应用
广告sprint>0
,如何调整我的代码

SELECT
    DATEPART(hh, DateCreated) AS Hour,
    AdvertisementId,
    COUNT(CASE WHEN IsPrinted = 1 THEN IsPrinted END) AS AdvertisementsPrinted
FROM 
    dbo.GaAnalytics
WHERE 
    AdvertisementId IS NOT NULL AND AdvertisementsPrinted > 0
GROUP BY
    DATEPART(hh, DateCreated),
    AdvertisementId
ORDER BY 
    AdvertisementsPrinted DESC

替换按计数冲刺的广告(如果IsPrinted=1,则为IsPrinted end)

有两个问题:

  • 其中,AdvertisementId不为NULL且AdvertisementsPrinted>0
    -
    AdvertisementsPrinted
    是一个聚合,因此它应该位于
    HAVING
    子句中
  • 您不能在查询的任何其他子句中使用
    SELECT
    中的别名,除非
    ORDER BY
    。这是因为
    SELECT
    是在其他子句(如
    WHERE
    groupby
    )之后计算的,而
    ORDER BY
    是最后一个子句
  • 因此,请将查询更改为:

    SELECT
    DATEPART(hh, DateCreated) as Hour,
    AdvertisementId,
    COUNT(case when IsPrinted = 1 then IsPrinted end) as AdvertisementsPrinted
    FROM dbo.GaAnalytics
    WHERE AdvertisementId IS NOT NULL
    GROUP BY
    DATEPART(hh, DateCreated),
    AdvertisementId
    HAVING COUNT(case when IsPrinted = 1 then IsPrinted end) > 0
    ORDER BY AdvertisementsPrinted DESC
    

    有广告冲刺>0@demas感谢您的介绍,但如果我在ORDER BY之前添加HAVING AdvertisementSprint>0,则我得到相同的错误它不起作用,我得到错误聚合可能不会出现在WHERE子句中,除非它位于HAVING子句或select列表中包含的子查询中,正在聚合的列是外部引用。感谢您的明确解释。
    SELECT
    DATEPART(hh, DateCreated) as Hour,
    AdvertisementId,
    COUNT(case when IsPrinted = 1 then IsPrinted end) as AdvertisementsPrinted
    FROM dbo.GaAnalytics
    WHERE AdvertisementId IS NOT NULL
    GROUP BY
    DATEPART(hh, DateCreated),
    AdvertisementId
    HAVING COUNT(case when IsPrinted = 1 then IsPrinted end) > 0
    ORDER BY AdvertisementsPrinted DESC