[英]How to make a query with multiple sums in a single row without subqueries?
I need a query which returns four different sums based on a column, but don't know how to do it without subqueries.我需要一个基于列返回四个不同总和的查询,但不知道如何在没有子查询的情况下执行此操作。
What I need to do is basically this: I have two tables, "caixa" and "movimentacao".我需要做的基本上是这样的:我有两个表,“caixa”和“movimentacao”。 The table "movimentacao" has a field "type", which ranges from 0 to 3, and a field "value", and need a query which returns the sum of value from each type of "movimentacao" belonging to a "caixa", but in a single row, so grouping by the type won't work.
表“movimentacao”有一个字段“type”,范围从0到3,还有一个字段“value”,需要一个查询,返回属于“caixa”的每种类型的“movimentacao”的值总和,但在一行中,因此按类型分组将不起作用。
So far my solution is:到目前为止,我的解决方案是:
SELECT
(SELECT SUM(value) FROM movimentacao where id_caixa = x.id_caixa and type = 0)
(SELECT SUM(value) FROM movimentacao where id_caixa = x.id_caixa and type = 1)
(SELECT SUM(value) FROM movimentacao where id_caixa = x.id_caixa and type = 2)
(SELECT SUM(value) FROM movimentacao where id_caixa = x.id_caixa and type = 3)
FROM caixa x
Is there a way to do this without these four subqueries, using joins instead?有没有办法在没有这四个子查询的情况下使用连接来做到这一点?
You can do this using aggregation: 您可以使用聚合执行此操作:
SELECT SUM( CASE WHEN m.type = 0 THEN x.value END ) as type_0,
SUM( CASE WHEN m.type = 1 THEN x.value END ) as type_1,
SUM( CASE WHEN m.type = 2 THEN x.value END ) as type_2,
SUM( CASE WHEN m.type = 3 THEN x.value END ) as type_3
FROM caixa x JOIN
movimentacao m
ON x.id_caixa = m.id_caixa;
You can do multiple OR
你可以做多个
OR
SELECT SUM(value) FROM movimentacao where id_caixa = x.id_caixa and type = 0 or type = 1 or type = 3
Or use BETWEEN
或者使用
BETWEEN
SELECT SUM(value) FROM movimentacao where id_caixa = x.id_caixa and type BETWEEN 0 AND 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.