3

我怎样才能在一个查询而不是这个查询中得到结果:

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

结果_1 = type0 ;

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

结果_2 = type1;

final_result = result_1 - result_2;

4

2 回答 2

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 ) 

SQLFiddle

于 2012-12-31T03:24:46.590 回答
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 回答