duanlinghe8417 2017-03-20 08:08
浏览 160
已采纳

MySql如何在1个查询中选择2个不同where条件的sum列

+-----+---------+--------+---------+
| PID | account | amount | balance |
+-----+---------+--------+---------+
|   1 |       1 |    100 |      dr |
|   2 |       5 |    100 |      cr |
|   3 |       2 |     30 |      dr |
|   4 |       1 |     30 |      cr |
|   5 |       1 |     50 |      cr |
|   6 |       4 |     50 |      dr |
+-----+---------+--------+---------+

I have the sample table above, I am using CI and I want to select sum the total amount of 'column amount WHERE column balance has value dr' minus total amount of 'column amount WHERE column balance has value cr'. Now how do I write this into just one query ??

What I'm currently doing is using 2 queries such as below

// Get total amount that has balance dr of account 1
$this->db->select_sum('amount');
$query = $this->db->get_where('table', array('account' => '1', 'balance' => 'dr');
$result = $query->result();
$total_dr = $result[0] -> amount;

// Get total amount that has balance cr of account 1
$this->db->select_sum('amount');
$query = $this->db->get_where('table', array('account' => '1', 'balance' => 'cr');
$result = $query->result();
$total_cr = $result[0] -> amount;

// Minus total_dr to total_cr
$total = $total_dr - $total_cr;

I think there must be a way to get $total without querying twice, but I couldn't find any lead in SO.

  • 写回答

3条回答 默认 最新

  • dongtang9855 2017-03-20 08:20
    关注
    SELECT
       account,
       SUM(CASE WHEN balance = 'dr' THEN amount
          WHEN balance = 'cr' THEN -amount
          ELSE 0
          END
       ) amount
    FROM
       table
    GROUP BY
       account
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案