SELECT
Monitor_Summary.Company_id AS CompanyId,
Monitor_Summary.Company_Name,
COUNT(1) AS Total,
(SELECT COUNT(1)
FROM MONITOR
WHERE ISNULL(MONITOR.IPWarning_ind, 0) = 1
AND MONITOR.Company_id = Monitor_Summary.Company_ID
AND MONITOR.Status_ind NOT IN (1,0)) AS NewWarnings
FROM
Monitor_Summary
GROUP BY
Monitor_Summary.Company_id, Monitor_Summary.Company_Name
HAVING
COUNT(1) > 2 AND NewWarnings > 1
我只想选择拥有超过1个NewWarnings的行。我收到错误说无效列,但不确定如何解决此问题。
谢谢,
答案 0 :(得分:2)
您需要将基本查询放在子查询或CTE中,以便可以参考NewWarnings
列:
;WITH CTE AS
(
SELECT
Monitor_Summary.Company_id AS CompanyId,
Monitor_Summary.Company_Name,
COUNT(1) AS Total,
(SELECT COUNT(1)
FROM MONITOR
WHERE ISNULL(MONITOR.IPWarning_ind, 0) = 1
AND MONITOR.Company_id = Monitor_Summary.Company_ID
AND MONITOR.Status_ind NOT IN (1,0)) AS NewWarnings
FROM
Monitor_Summary
GROUP BY
Monitor_Summary.Company_id, Monitor_Summary.Company_Name
)
SELECT
CompanyId,
Company_Name,
Total,
NewWarnings
FROM
CTE
WHERE
Total > 2 AND NewWarnings > 1
答案 1 :(得分:0)
SELECT
仅在 HAVING
执行后才会被评估。因此,您无法在NewWarnings
子句中使用HAVING
。
解决此问题的一种方法是使用SELECT
实现CROSS APPLY
子句的相关子查询:
SELECT Monitor_Summary.Company_id AS CompanyId,
Monitor_Summary.Company_Name,
COUNT(1) AS Total,
x.NewWarnings
FROM Monitor_Summary
CROSS APPLY (
SELECT COUNT(1)
FROM MONITOR
WHERE ISNULL(MONITOR.IPWarning_ind, 0) = 1
AND MONITOR.Company_id = Monitor_Summary.Company_ID
AND MONITOR.Status_ind NOT IN (1,0)
) AS x(NewWarnings)
WHERE x.NewWarnings > 1
GROUP BY Monitor_Summary.Company_id,Monitor_Summary.Company_Name
HAVING COUNT(1) > 2
这样您就可以在查询的NewWarnings
子句中使用WHERE
字段。