【问题标题】:MySql how to select sum column with 2 different where conditions in 1 queryMySql如何在1个查询中选择具有2个不同where条件的总和列
【发布时间】:2017-03-20 08:08:43
【问题描述】:
+-----+---------+--------+---------+
| 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 |
+-----+---------+--------+---------+

我有上面的示例表,我正在使用 CI,我想选择“列金额 WHERE 列余额值为 dr”的总金额减去“列金额 WHERE 列余额值为 cr”的总金额。现在如何将其写入一个查询中??

我目前正在做的是使用 2 个查询,如下所示

// 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;

我认为必须有一种方法可以在不查询两次的情况下获得 $total,但我在 SO 中找不到任何线索。

【问题讨论】:

    标签: php mysql codeigniter


    【解决方案1】:
    SELECT
       account,
       SUM(CASE WHEN balance = 'dr' THEN amount
          WHEN balance = 'cr' THEN -amount
          ELSE 0
          END
       ) amount
    FROM
       table
    GROUP BY
       account
    

    【讨论】:

    • 您先生真了不起。非常感谢您提供非常简单高效的查询。
    【解决方案2】:

    您可以使用 SQL 查询来做到这一点:

    SELECT 
        SUM(CASE WHEN balance = 'dr' THEN amount ELSE NULL END) AS sum_dr,
        SUM(CASE WHEN balance = 'cr' THEN amount ELSE NULL END) AS sum_cr
    FROM table
    WHERE account = 1
    AND balance IN ('dr', 'cr')
    

    将上面的查询放到 CI query() 方法中,并从结果数组中获取列:“sum_dr”和“sum_cr”。

    【讨论】:

    • 非常感谢您的回答。
    【解决方案3】:

    这样的事情应该可以解决问题:

    SELECT SUM(IF(balance = 'dr', amount, (-1) * amount))
    FROM table
    WHERE account = 1
    AND balance IN ('dr', 'cr')
    

    【讨论】:

    • 非常感谢您的回答。 :)
    猜你喜欢
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多