0

Can MySQL detect the columns created using AS?

Example;

SUM( Mark1 + Mark2) AS '2022_SUM'
SUM( Mark3 + Mark4) AS '2021_SUM'
(2022_SUM + 2021_SUM) AS 'SUM1'

It hits unknown column in field list.

newbie112
  • 45
  • 1
  • 8
  • 1
    Please provide a **complete** SQL statement., and take a look at [Using Column Alias in Same SELECT Clause](https://stackoverflow.com/questions/28860303/using-column-alias-in-same-select-clause) – Luuk Dec 30 '22 at 11:10
  • Hi Luuk, thanks. Using a user defined variable makes it so the sum of the current row has the sum of the previous row. Any way to solve this? – newbie112 Dec 30 '22 at 11:37
  • "Using a user defined variable" I cannot see what you are doing with user defined variables, which seems not needed here. – Luuk Dec 30 '22 at 11:39
  • Sorry, i was referring to the link you gave me. they use a variable to solve column alias not being able to be detected by select clause. – newbie112 Dec 30 '22 at 11:43

1 Answers1

0

Just write:

SELECT
   SUM(Mark1 + Mark2) as '2022_SUM',
   SUM(Mark3 + Mark4) as '2021_SUM',
   SUM(Mark1 + Mark2) + SUM(Mark3 + Mark4) as 'SUM1'
FROM someTableName

OR

SELECT
   2022_SUM,
   2021_SUM,
   2022_SUM + 2021_SUM as 'SUM1'
FROM (
   SELECT
      SUM(Mark1 + Mark2) as '2022_SUM',
      SUM(Mark3 + Mark4) as '2021_SUM'
   FROM someTableName 
) x
Luuk
  • 12,245
  • 5
  • 22
  • 33