Search code examples
sqlrmysql

Trying to return rows based on condition of summed columns


Apologies if this has been asked. For what I thought was a relatively simple question, I couldn't seem to find the answer in my searches.

linesInserted and linesDeleted are two columns in the table. I'm trying to return rows where linesInserted + linesDeleted >= 200. The query I have is

SELECT *, (linesInserted + linesDeleted) as total
FROM table
WHERE total >= 200
GROUP BY id

This doesn't work as I'm getting an error saying:

Unknown column 'TOTAL' in where clause

I'm using RMySql for those curious.


Solution

  • If you sum over linesInserted + linesDeleted then there would be no problem:

    SELECT id, sum(linesInserted + linesDeleted) as total
    FROM table
    GROUP BY id
    having total >= 200