Skip to content
Advertisement

How to use the results of a query to filter a table comparing one field to the result?

I want to filter a table showing only the rows where total is between ± 3 standard deviations from the average.

The query I’m using is this:

But I’m getting the error:

An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

Advertisement

Answer

Try something like this. I have added some sample data as your question has not given any data and schemas. You need to use group by clause when you use Aggregate functions in our queries. I suggest you to refer to Group by and aggregate functions in SQL server.

Sample data scripts:

1st way: You need to use GROUP BY and HAVING when use Aggregate functions in filters. Having can filter by groups.

2nd way: Use Aggregations as a sub query. in that case you don’t need to use group by or having as you use subquery in where clause.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement