错误:尝试过滤别名列名时无效的列名称

时间:2014-07-10 07:07:18

标签: sql sql-server tsql

以下代码给出了这个错误:

  

Msg 207,Level 16,State 1,Line 6
  列名称无效' AdvertisementsPrinted'。

我需要应用AdvertisementsPrinted > 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

2 个答案:

答案 0 :(得分:2)

有两个问题:

  1. WHERE AdvertisementId IS NOT NULL AND AdvertisementsPrinted > 0 - AdvertisementsPrinted是一个聚合,因此它应该在HAVING子句中。
  2. 除了SELECT之外,您不能在查询的任何其他子句中使用ORDER BY中的别名。这是因为SELECT是在WHEREGROUP BY等其他条款之后进行评估的,而ORDER BY是最后一个条款。
  3. 因此,请将您的查询更改为:

    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
    

答案 1 :(得分:0)

用COUNT替换AdvertisementsPrinted(IsPrinted = 1然后IsPrinted结束时的情况)

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 COUNT(case when IsPrinted = 1 then IsPrinted end)> 0
GROUP BY
DATEPART(hh, DateCreated),
AdvertisementId