1

是否可以将这两个查询合并为一个查询?

SELECT sum(amount) as credit FROM statement WHERE userId= '33003' AND debitOrCredit = '1' AND actionDate <= '2012-10-17';

SELECT sum(amount) as debit FROM statement WHERE userId= '33003' AND debitOrCredit = '0' AND actionDate <= '2012-10-17';

所以我得到了结果:

| credit  | debit  |   
|   90    |   60   |
4

5 回答 5

3

您可以CASE在 SUM 中使用:

SELECT sum(CASE WHEN debitOrCredit = '1' THEN amount ELSE 0 END) as credit,
       sum(CASE WHEN debitOrCredit = '0' THEN amount ELSE 0 END) as debit
FROM statement WHERE userId= '33003' AND actionDate <= '2012-10-17';
于 2012-10-17T09:29:08.930 回答
2

CASE在你的SELECT条款中使用

SELECT sum(CASE WHEN debitOrCredit = '1' THEN amount ELSE 0 END) as credit,
       sum(CASE WHEN debitOrCredit = '0' THEN amount ELSE 0 END) as debit
FROM   statement 
WHERE  userId= '33003'  AND 
       actionDate <= '2012-10-17';
于 2012-10-17T09:28:43.200 回答
0

像这样使用。

SELECT sum(a.amount) as credit,sum(b.amount) as debit FROM statement a left join statement b
on a.userId=b.userId
 WHERE a.userId= '33003' AND a.debitOrCredit = '1' AND b.debitOrCredit = '0' AND a.actionDate <= '2012-10-17' AND b.actionDate <= '2012-10-17' ;

-- 如果此答案回答了您的问题,请标记回答...

于 2012-10-17T09:34:27.623 回答
0

感谢您的帮助。这就是我在 Zend 框架中使用它的方式:

$sql = $this->_dba->select()
    ->from('statement', array(
        "credit" => "sum(CASE WHEN debitOrCredit = '1' THEN amount ELSE 0 END)",
        "debit" => "sum(CASE WHEN debitOrCredit = '0' THEN amount ELSE 0 END)"))
    ->where('userId = ?', $userId)
    ->where('actionDate <= ?', $date);

    try
    {
        $result = $this->db->fetchRow($sql);
        //process result here       
    }
    catch (Exception $e)
    {
        throw new Exception("Error on ...... ");
    }
于 2012-10-18T08:48:09.577 回答
-1

试试这个

SELECT sum(case when debitOrCredit = '1' then amount else 0 end) as credit, sum(case when debitOrCredit = '2' then amount else 0 end) as debit FROM statement WHERE userId= '33003' AND actionDate <= '2012-10-17'

于 2012-10-17T09:40:05.500 回答