以下代码给出了这个错误:
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
答案 0 :(得分:2)
有两个问题:
WHERE AdvertisementId IS NOT NULL AND AdvertisementsPrinted > 0
- AdvertisementsPrinted
是一个聚合,因此它应该在HAVING
子句中。SELECT
之外,您不能在查询的任何其他子句中使用ORDER BY
中的别名。这是因为SELECT
是在WHERE
或GROUP BY
等其他条款之后进行评估的,而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
答案 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