Skip to content
Advertisement

Summing the total of 4 alias

I have the following query:

Which outputs:

I want to have another column called “total” which has the sum of all 4 aliases.

Advertisement

Answer

Since you can’t use column aliases in the SELECT clause, there’s a couple of other ways you can do this. Either add another conditional aggregation to your query:

Note that this assumes that only one of s1, s2, s3 or s4 will be equal to fel for any given row.

The more robust method is to use your original query as a subquery:

Note that since MySQL treats a boolean expression in a numeric context as either 1 (true) or 0 (false) you can simplify these queries as follows:

Doing this removes the issue the first query had of requiring that only one of s1, s2, s3 or s4 will be equal to fel for any given row.

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