2

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.

3
  • Which RDBMS? If MySQL, you're going to need a HAVING clause. Commented Jul 30, 2013 at 23:49
  • 1
    Is there a typo in between Table and 1? Other than that, you're query should run fine (sqlfiddle.com/#!2/6c98b/1)... What are your desired results? Commented Jul 30, 2013 at 23:49
  • Yes sorry there was a typo when I generalised the data. Commented Jul 31, 2013 at 0:34

3 Answers 3

3

There's a circular dependency on your filtering. You want to only select records where the count is 3, but you must count them before you can determine this. This means that you need a HAVING clause rather than a WHERE clause (to filter on an aggregate function, you always need a HAVING clause).

Furthermore, you can't use an aliased column name for an aggregate function in a WHERE or HAVING clause. You have to repeat the function in the filtering:

Select ID, Count(ID) As Count_ID
From Table1
Group By ID
HAVING Count(ID) = 3;
Sign up to request clarification or add additional context in comments.

Comments

2

In this case, because you're referencing an aggregate function and a grouping, you have to use a HAVING clause.

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

1 Comment

Thanks but Corbin beat you to it but seconds by the looks of it.
1

Alternatively you can use this too:

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

1 Comment

This method also works, but going to use HAVING Instead. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.