【问题标题】:mySQL select based on sum of rows compared to another field valuemySQL 根据与另一个字段值相比的行总和进行选择
【发布时间】:2014-02-23 20:00:43
【问题描述】:

我有一张发票项目表。单个交易可能导致多个借项和多个贷项共享相同的 invoice_set_id,我需要将借项的总和与贷项的总和进行比较,如果 sum(debits) > sum 则将 invoice_set_id 添加到结果集中(学分)。如果没有贷记金额的行,它也应该添加到结果中。使用 mySQL。谢谢你的帮助。示例表和结果如下:

invoice_item_id  invoice_set_id  credit_debit  amount
62                a22             debit         15.00
63                a22             debit          8.00
64                a22             credit        23.00
65                b23             debit         44.00
66                c55             debit         15.00
67                c55             debit          2.00
67                c55             credit         8.00

鉴于以上,结果集应该是:

invoice_set_id
b23
c55

解释:a22 不返回是因为借方和贷方相等,b23 是因为有借方没有贷方返回,c55 是因为借方之和大于单个贷方。

感谢您对此提供的任何帮助。实际查询涉及更多,但我认为这个特殊问题是我需要帮助的全部。

【问题讨论】:

    标签: mysql


    【解决方案1】:

    您只需使用group byhaving 即可:

    select invoice_set_id
    from t
    group by invoice_set_id
    having sum(case when credit_debit = 'debit' then amount else 0 end) > sum(case when credit_debit = 'credit' then amount else 0 end) ;
    

    having 子句的另一种表达方式是:

    having sum(case when credit_debit = 'debit' then amount
                    when credit_debit = 'credit' then - amount
                    else 0
               end) > 0;
    

    【讨论】:

    • 美丽。简短而甜蜜。我测试了示例 1,结果正是我所追求的。谢谢。
    猜你喜欢
    • 2016-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多