Skip to content
Advertisement

How to use sum in where clause in SQL?

I want to execute this query:

Select Environment, SUM(Scores) as `Scores`,SUM(Clicks) as `Clicks` 
      from Example.table 
      where Scores > sum(Scores)
      group by Environment

But it throws the following error:

Aggregate function SUM not allowed in WHERE clause at [4:27]

whereas for the case of having: having Scores > sum(Scores) doesn’t allow me to keep Scores. What is the right way to implement this?

Advertisement

Answer

Your query should be like this:

Select Environment
       ,Scores
       ,SUM(Scores) as `Scores`
       ,SUM(Clicks) as `Clicks`  
       from TABLE 
      group by Environment, Scores
      HAVING (Scores > sum(Scores))

You need to include Score and group by that also (even if you don’t need it).

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