1

これら 2 つのクエリを 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

CASESUM 内で使用できます。

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 に答える