如何在没有子查询的情况下在一行中进行多个总和的查询?

时间:2018-11-08 23:02:02

标签: mysql sql

我需要一个查询,该查询根据一列返回四个不同的总和,但不知道如何在没有子查询的情况下进行操作。

基本上我需要做的是:我有两个表,“ caixa”和“ movimentacao”。表“ movimentacao”具有一个字段“ type”(范围从0到3)和一个字段“ value”,并且需要一个查询,该查询返回属于“ caixa”的每种“ movimentacao”类型的值之和,但只能排成一行,因此按类型分组是行不通的。

到目前为止,我的解决方案是:

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

是否有一种方法可以在没有这四个子查询的情况下使用联接代替呢?

2 个答案:

答案 0 :(得分:3)

您可以使用聚合来实现:

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;

答案 1 :(得分:-1)

您可以执行多个OR

SELECT SUM(value) FROM movimentacao where id_caixa = x.id_caixa and type = 0 or type = 1 or type = 3

或 使用BETWEEN

SELECT SUM(value) FROM movimentacao where id_caixa = x.id_caixa and type BETWEEN 0 AND 3