Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use the result of a SUM function in the WHERE clause of MSSQL?

For example suppose I have

SELECT sum(...) as total

Can I do something like

WHERE total > 10

When I try that actual syntax I get an error

invalid column name 'total'

like image 657
Daniel Avatar asked Jan 23 '26 10:01

Daniel


2 Answers

if you are using sum with group by

select sum(...) 
group by Col1 
having sum(...) > 10

without group by

select sum(...) 
having sum(...) > 10 

if you want to use a column name you need to place the query in subquery

SELECT * FROM (
   SELECT sum(...) as total 
) as T
WHERE total > 10
like image 123
Serkan Arslan Avatar answered Jan 26 '26 01:01

Serkan Arslan


"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".

HAVING is like WHERE with aggregate functions, or you could use a subquery.

select name, sum(amount) as total
from table
group by name
having sum(amount) > 10

Or

select * from(
   select name, sum(amount) as total 
) as temp
where temp.total > 10
like image 36
Hasan Fathi Avatar answered Jan 26 '26 02:01

Hasan Fathi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!