1

What is the correct way to write an SQL Query so I can use the output of a function that I have used in the Select Statement in the Where clause?

Data Table:

ID    Count_ID
111   2
111   2
222   3
222   3
222   3
333   1

Query:

Select ID, Count(Table1.ID) As Count_ID
From Table1
Where Count_ID = 3
Group By ID

It gives me invalid column name currently in there Where Clause for Count_ID.

4

3 回答 3

3

您的过滤存在循环依赖关系。您只想选择计数为 3 的记录,但您必须先对它们进行计数,然后才能确定这一点。这意味着您需要一个 HAVING 子句而不是 WHERE 子句(要过滤聚合函数,您总是需要一个 HAVING 子句)。

此外,您不能在 WHERE 或 HAVING 子句中为聚合函数使用别名列名。您必须在过滤中重复该功能:

Select ID, Count(ID) As Count_ID
From Table1
Group By ID
HAVING Count(ID) = 3;
于 2013-07-30T23:52:53.367 回答
2

在这种情况下,因为您要引用聚合函数和分组,所以您必须使用HAVING子句。

 Select ID, Count(Table1.ID) As Count_ID
   From Table1
        Group By ID
        Having Count(Table1.ID)  = 3
于 2013-07-30T23:52:38.027 回答
1

或者,您也可以使用它:

SELECT ID, Count_ID
FROM
  (SELECT ID, Count(ID) AS Count_ID
   FROM Table1
   GROUP BY ID) Calced
WHERE Calced.Count_ID = 3;

http://sqlfiddle.com/#!4/f2a73/5

于 2013-07-31T00:27:22.293 回答