mysql SUM CASE自连接

时间:2012-08-07 05:48:01

标签: mysql sum case self self-join

我需要一些关于此查询的帮助

这是我查询的实际结果

price received   qty recieved    price release  qty release     
  10.30              10                0             0                
   0                  0              10.30           2  
   0                  0              10.30           1
  19.20              20               0              0
   0                  0              19.20           5                      
   0                  0              19.20           3                
   0                  0              19.20           1                

在我的查询中使用此代码

$result = mysql_query("SELECT *, 
     SUM(CASE WHEN qtyreceived > 0 THEN qtyreceived END) AS qtyrec,
     SUM(CASE WHEN  qtyrelease > 0 THEN qtyrelease END) AS qtyrel 
     FROM stockledger 
     WHERE stockdesc= '$_POST[desc]' GROUP BY pricerelease,pricereceived ");    

结果是

价格收到qtyreceived价格释放qtyrelease bal      10.30 10 10      19.20 20 20                                       10.30 3 -3                                       19.20 9 -9

我希望以这种方式查看结果,这样我就能得到2个价格的剩余数字

 price received       qtyreceived    price release  qtyrelease    bal
         10.30            10              10.30           3        7
         19.20            20              19.20           9        11

感谢.....;

1 个答案:

答案 0 :(得分:1)

从查看您的数据,我认为它将基于价格。对?试试这个。

SELECT  a.PriceReceived,
        a.qtyreceived,
        b.priceRelease,
        b.qtyRelease,
        (a.bal + b.bal) as bal
FROM    stockledger a 
            INNER JOIN stockledger b
                ON a.priceReceived = b.priceRelease

或其他替代方案是

SELECT  a.PriceReceived,
        a.qtyreceived,
        b.priceRelease,
        b.qtyRelease,
        (a.qtyreceived - b.qtyRelease) as bal
FROM    stockledger a 
            INNER JOIN stockledger b
                ON a.priceReceived = b.priceRelease

SQLFiddle Demo