0

我的数据库有这样的结构: 在此处输入图像描述

“Movimientos”表记录了我系统的所有费用和付款。'Cargos' 表在 'Movimientos' 上保存每笔费用的一些元数据,而 'Abonos' 表在 'Movimientos' 上保存每笔付款的一些元数据。

如何编写一个查询来汇总 'Movimientos' 中的所有记录,其中 'Abonos.tipo_abono' 和 'Cargos.tipo_cargo' 有一些标准?

我有一个查询已经对“Movimientos”求和,但我无法添加“Abonos”和“Cargos”表添加更多条件的部分。

SELECT SUM(M.monto) as monto, SUM(M.interes) as interes, SUM(M.iva) as iva, SUM(M.capital) as capital
                FROM movimientos AS M
                JOIN acreditados AS A ON A.id_acreditado = M.id_acreditado
                JOIN creditos AS C ON C.id_credito = A.id_credito
                WHERE  C.id_credito = 29

假设我想修改最后一个查询以仅对 'Abono.tipo_abono'=1 和 'Cargos.tipo_cargo'=1 的记录求和,我该怎么做?

4

1 回答 1

3

如果您的关系是一对一的,您只需将表格加入其中并按您的条件进行过滤。如果相关记录始终存在,则将其设为内部连接。如果相关表可能没有记录,则应为 aLEFT OUTER JOIN中指定的条件,JOIN而不是WHERE.

SELECT SUM(M.monto) as monto,
    SUM(M.interes) as interes,
    SUM(M.iva) as iva,
    SUM(M.capital) as capital
FROM movimientos AS M
JOIN acreditados AS A ON A.id_acreditado = M.id_acreditado
JOIN creditos AS C ON C.id_credito = A.id_credito
LEFT OUTER JOIN Abonos AS AB on AB.id_movimiento = M.id_movimiento AND AB.tipo_abono = 1
LEFT OUTER JOIN Cargos AS CG on CG.id_movimiento = M.id_movimiento AND CG.tipo_cargo = 1
WHERE  C.id_credito = 29

但是,如果您的关系是多对一的,这将通过包含多movimientos行来影响您的总和。改用一个EXISTS子句:

SELECT SUM(M.monto) as monto,
    SUM(M.interes) as interes,
    SUM(M.iva) as iva,
    SUM(M.capital) as capital
FROM movimientos AS M
JOIN acreditados AS A ON A.id_acreditado = M.id_acreditado
JOIN creditos AS C ON C.id_credito = A.id_credito
WHERE  C.id_credito = 29
AND EXISTS (SELECT 1
    FROM Abonos AB
    WHERE AB.id_movimiento = M.id_movimiento
    AND tipo_abono = 1
)
AND EXISTS (SELECT 1
    FROM Cargos CG
    WHERE CG.id_movimiento = M.id_movimiento
    AND tipo_cargo = 1
)
于 2012-10-25T16:49:43.947 回答