简体   繁体   中英

Combine two MySQL queries to one

Is it possible to combine these two queries into one query?

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

so I get the result:

| credit  | debit  |   
|   90    |   60   |

You could use CASE within your 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';

use CASE in your SELECT clause

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

Use like this.

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

-- Mark answered if this answer answers your question...

Thank you for your help. This is how I used it in Zend framework:

$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 ...... ");
    }

尝试这个

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM