Search code examples
mysqlsqlcountsumcalculated-columns

In MySQL, can we use the COUNT and SUM value to calculate a value in another output column using a single SELECT?


Lets say we have something like:

SELECT COUNT(IF(Column1 = 1, NULL, 1)) AS "A", SUM(Column2) AS "B" FROM MyDatabase;

On the same query, can we add a column that would be A * B for example with one single SELECT overall?


Solution

  • You need to either repeat the expression, or turn it to a subquery and do the computation in the outer query. Your expression is not that complicated (and can be simplified, as shown below), so I would go for the first option here:

    SELECT 
        SUM(Column1 = 1) a, 
        SUM(Column2) b,
        SUM(Column1 = 1) * SUM(Column2) c
    FROM MyDatabase;