3

このクエリではなく、1 つのクエリだけで結果を取得するにはどうすればよいですか。

SELECT SUM(`quantity`) as type0 FROM `fruits_delivery` 
    WHERE `fid`='1001' AND `type`=0;

結果_1 = タイプ0;

SELECT SUM(`quantity`) as type1 FROM `fruits_delivery`  
    WHERE `fid`='1001' AND `type`=1;

結果_2 = タイプ1;

最終結果 = 結果 1 - 結果 2;

4

2 に答える 2

10

または、次を使用して行うこともできますCASE

SELECT  SUM(CASE WHEN type = 0 THEN quantity ELSE 0 END) -
        SUM(CASE WHEN type = 1 THEN quantity ELSE 0 END)
          AS final_result
FROM    fruits_delivery
WHERE   fid = '1001'
于 2012-12-31T03:31:57.480 に答える
10

これを使うべきです

SELECT sum(IF(`type`=0, `quantity`, 0))-sum(IF(`type`=1, `quantity`, 0)) 
        AS    `final_result` 
        FROM   `fruits_delivery` 
        WHERE  `fid` = '1001' 
               

sqlfiddle


古い回答

SELECT T1.result - T2.result AS `final_result` 
FROM   (SELECT Sum(`quantity`) AS result, 
               `fid` 
        FROM   `fruits_delivery` 
        WHERE  `fid` = '1001' 
               AND `type` = 0 
        LIMIT  1) AS T1 
       JOIN (SELECT Sum(`quantity`) AS result, 
                    `fid` 
             FROM   `fruits_delivery` 
             WHERE  `fid` = '1001' 
                    AND `type` = 1 
             LIMIT  1) AS T2 
         ON ( T1.fid = T2.fid ) 

SQLフィドル

于 2012-12-31T03:24:46.590 に答える