Pittor Pittor - 7 months ago 15
SQL Question

SUM() the results of GROUP BY column

Table 'volcado': id, reserva, cantidad

With the following query:

SELECT (CASE
WHEN sum(cantidad) > 0 THEN 1
WHEN sum(cantidad) <= 0 THEN 0
END) AS suma
FROM volcado
GROUP BY reserva


The result is:

╔══════╗
║ suma ║
╠══════╣
║ 1 ║
║ 1 ║
║ 0 ║
║ 1 ║
║ 0 ║
╚══════╝


I need the result of the query would be: 3

How can I SUM() the rows of 'suma' on the same query?

I don't get it run with:

SELECT SUM(SELECT (CASE
WHEN sum(cantidad) > 0 THEN 1
WHEN sum(cantidad) <= 0 THEN 0
END) AS suma FROM volcado GROUP BY reserva)
FROM volcado


Error:


Subquery returns more than 1 row


Thanks in advance.

Answer

Try this way

SELECT SUM(a.suma) from 
    (SELECT (CASE
        WHEN sum(cantidad) > 0 THEN 1
        WHEN sum(cantidad) <= 0 THEN 0
        END) AS suma FROM volcado GROUP BY reserva)a
Comments