Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reuse "sum(table_column) as x"

Tags:

sql

mysql

sum

I have a problem with an SQL query.

SELECT SUM(table_colum) AS value, SUM(value * 3) AS value2 FROM table;

You need to know this is a short representation of my whole query.

The error:

Unknown column 'value' in 'field list'

Is there a way to reuse value in another SUM()?

like image 580
Remy Strijker Avatar asked Dec 22 '22 00:12

Remy Strijker


2 Answers

You can just do:

SELECT SUM(table_colum) AS value, SUM(SUM(table_colum) * 3) AS value2 FROM table;

Internally, the server will only do the SUM(table_colum) calculation once and use the result twice.

like image 50
Nik Avatar answered Feb 03 '23 02:02

Nik


I suppose you could write

SELECT value, SUM(value * 3) AS value2
  FROM ( SELECT SUM(table_column) AS value
           FROM table
       ) AS t
;

But as I mentioned in a comment above, I'm not sure what you would want this for. SUM(table_column) is just a single value, so the SUM of it is just the same value. So you'd get the same result by writing:

SELECT value, value * 3 AS value2
  FROM ( SELECT SUM(table_column) AS value
           FROM table
       ) AS t
;

without the second SUM.

like image 43
ruakh Avatar answered Feb 03 '23 04:02

ruakh