mysql查询,用于从一个表中选择结果并插入另一个表中

时间:2013-05-21 12:37:00

标签: mysql

先生..你可以告诉我这个plz的查询

表1

--------------------------------
stock_name|temple|quantity|type
--------------------------------
rice      |shiva |  32    |purchase
rice      |shiva |  10    |issue
wheat     |ganesh|  50    | purchase
wheat     |ganesh|  45    | issue   
ghee      |ganesh|  50    | purchase
ghee      |ganesh|   5    | issue   

表2中的预期产出

--------------------------------
stock_name|temple|quantity|
--------------------------------
rice      |shiva |  22    |
wheat     |ganesh|  5     | 
ghee      |ganesh|  45    |

1 个答案:

答案 0 :(得分:3)

这里的答案与您发布的其他问题一样

INSERT INTO secondTable (stock_name,temple,quantity)
SELECT  stock_name,
        temple,
        SUM(CASE WHEN type = 'purchase' 
                     THEN quantity 
                     ELSE quantity * -1 
                 END) quantity
FROM    firstTable
GROUP   BY stock_name, temple