表'volcado':id,reserva,cantidad
使用以下查询:
SELECT (CASE
WHEN sum(cantidad) > 0 THEN 1
WHEN sum(cantidad) <= 0 THEN 0
END) AS suma
FROM volcado
GROUP BY reserva
结果是:
╔══════╗
║ suma ║
╠══════╣
║ 1 ║
║ 1 ║
║ 0 ║
║ 1 ║
║ 0 ║
╚══════╝
我需要查询的结果是:3
如何在同一个查询中SUM()'suma'的行?
我不知道它运行:
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
错误:
子查询返回超过1行
提前致谢。
答案 0 :(得分:2)
试试这种方式
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
答案 1 :(得分:1)
这应该有效,将子查询用作表而不是列。
SELECT SUM(suma) from
(SELECT (CASE
WHEN sum(cantidad) > 0 THEN 1
WHEN sum(cantidad) <= 0 THEN 0
END) AS suma FROM volcado GROUP BY reserva)
答案 2 :(得分:0)
您可以使用CTE:
;WITH cte AS
(SELECT CASE
WHEN sum(cantidad) > 0 THEN 1
WHEN sum(cantidad) <= 0 THEN 0
END suma
FROM volcado
GROUP BY reserva)
SELECT sum(suma)
FROM cte
答案 3 :(得分:0)
如果您愿意,可以简化查询。因此,不要使用case
使用having
:
SELECT COUNT(*)
FROM (SELECT reserva
FROM volcado
GROUP BY reserva
HAVING SUM(cantidad) > 0
) r;