mysql SQL中的多个查询

k97glaaz  于 2022-11-28  发布在  Mysql
关注(0)|答案(1)|浏览(152)

我有一个按物料事务处理名称列出的表,我希望显示类似表B的数据
| 项目名称|异动型态|重量|
| - -|- -|- -|
| A级|发放物料|六十|
| B|发放物料|八十|
| A级|退回物料|二十个|
| B|退回物料|10个|
| A级|发放物料|二十个|
| B|发放物料|10个|
我希望结果如下表表B
| 项目名称|发放物料|退回物料|
| - -|- -|- -|
| A级|八十|二十个|
| B|九十|10个|

$query = "SELECT item_name, SUM(material_wt) AS issue_material WHERE transaction_type = 'Issue Material' FROM material_transaction GROUP BY item_name UNION ALL SELECT item_name, SUM(material_wt) AS return_material WHERE transaction_type = 'Reject Material' FROM material_transaction GROUP BY item_name";
                        $select_query_table = mysqli_query($connection,$query);
                        while($run_select_query = mysqli_fetch_assoc($select_query_table)){
                 
                     $item_name = $run_select_query['item_name'];  
                     $wt = $run_select_query['material_wt'];  
                        echo "<td>$item_name</td>";                          
                       echo "<td>$wt</td>";                          
                        echo "</tr>";
                   
                    }
qkf9rpyu

qkf9rpyu1#

您可以使用条件聚集:

SELECT
    item_name,
    SUM(CASE WHEN transaction_type = 'Issue Material'
             THEN Weight ELSE 0 END) AS Issue_Material,
    SUM(CASE WHEN transaction_type = 'Return Material'
             THEN Weight ELSE 0 END) AS Return_Material
FROM material_transaction
GROUP BY item_name;

相关问题