Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php MySql如何在1个查询中选择具有2个不同where条件的sum列_Php_Mysql_Codeigniter - Fatal编程技术网

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

Php MySql如何在1个查询中选择具有2个不同where条件的sum列,php,mysql,codeigniter,Php,Mysql,Codeigniter,我有上面的示例表,我正在使用CI,我想选择“列余额有值dr的列金额”的总额减去“列余额有值cr的列金额”的总额。现在我如何将其写入一个查询 我目前正在做的是使用如下2个查询 +-----+---------+--------+---------+ | PID | account | amount | balance | +-----+---------+--------+---------+ | 1 | 1 | 100 | dr | | 2 | 5

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

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

+-----+---------+--------+---------+
| 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 |
+-----+---------+--------+---------+

我想一定有办法不必查询两次就可以得到$total,但我找不到任何线索。

像这样的方法应该可以做到:

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

您可以使用SQL查询执行此操作:

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

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

您真是太棒了。非常感谢您的简单高效的查询。非常感谢您的回答。非常感谢您的回答。:)
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')
SELECT
   account,
   SUM(CASE WHEN balance = 'dr' THEN amount
      WHEN balance = 'cr' THEN -amount
      ELSE 0
      END
   ) amount
FROM
   table
GROUP BY
   account