mysql在同一个表上获得两个sum的差异

时间:2012-12-31 03:19:45

标签: mysql sql sum

我如何只用一个查询而不是这个查询得到结果:

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

result_1 = type0;

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

result_2 = type1;

     

final_result = result_1 - result_2;

2 个答案:

答案 0 :(得分:9)

你应该使用这个

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

答案 1 :(得分:9)

或者,您也可以使用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'