mysql - 查看mysql中计算余额

标签 mysql view

我在 mysql 中有一个 View ,运行良好并正确显示结果。

   SELECT m.`id_cuota`, m.`clv_cuota`, m.`debe`, m.`haber`,
   (select sum(debe) - sum(haber)
    from cuotas m2
    where m2.id_cuota <= m.id_cuota
   ) as balance
   FROM `cuotas` m
   ORDER BY m.`id_cuota` DESC;


  id_cuota  clv_cuota  debe    haber     balance
  22          115      25.00    0.00     125.00
  21          115       0.00  150.00     100.00
  20          115      50.00    0.00     250.00
  19          116     100.00    0.00     200.00
  18          115     100.00    0.00     100.00

我想知道如何进行查询,但结果是例如。 “clv_cuotas=115”。这就是结果。

  id_cuota  clv_cuota  debe    haber     balance
  22          115      25.00    0.00      25.00
  21          115       0.00  150.00       0.00
  20          115      50.00    0.00     150.00
  18          115     100.00    0.00     100.00

最佳答案

在不重做查询本身的情况下,问题是运行总余额需要 116 才能获得正确的余额,只有在计算出值之后,您才能删除它们。因此,包装在一个查询中,例如:

select PQ.*
   from  ( your existing query )  PQ
   where PQ.clv_cuto = 115

这样,内部行是根据所有 clv_cuto 值计算的,并且仅在事后排除。

注意:这应该显示您期望从第一个查询中获得的正确余额,仅返回这 115 个条目。

为了回答/澄清您的需求,由于您只关心帐户 115 的净事件,因此只需将其作为您的 where 子句即可。它需要应用于查询的内部和外部部分。

SELECT m.`id_cuota`, m.`clv_cuota`, m.`debe`, m.`haber`,
   (select sum(debe) - sum(haber)
    from cuotas m2
    where m2.id_cuota <= m.id_cuota
      AND m2.clv_cuota = 115
   ) as balance
   FROM `cuotas` m
   WHERE m2.clv_cuota = 115
   ORDER BY m.`id_cuota` DESC;

关于mysql - 查看mysql中计算余额,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27640489/

相关文章:

SQL - 如何找到列中的最高数字?

php - Codeigniter 很少不会加载数据库连接

数据库设计: a 'code' table that get referenced by other entities

android - 以编程方式在 ScrollView 中添加一个 View

ios - 辅助功能:专注于一个 View

MySQL:VIEW 语句:使用 View 和聚合函数

mysql - 将两列分组,对另一列中的相应值进行计数,并将计数放入两列中

php - php 中时间戳的平均每日金额

android - 我怎样才能让这个 View 进入我的程序? (主题链接)

java - jdbcTemplate 为 null 并抛出空指针异常