非常需要帮助。所以我有2个表:
我的交易表包含以下内容。列:
transaction_id(int), alloc_id(int), month_sold(varchar), Quantity_sold(int)
我的分配表包含以下内容。列:
alloc_id(int),item_allocation(int),item_name(varchar)
我只想显示每月出售而不是出售的商品的摘要,以及它们的分配。急需一些帮助。预先谢谢你!
我尝试过,但是我无法获得未售出的分配。
SELECT transaction.transaction_id, allocations.item_allocation,
sum(if (transaction.month_sold = 'JANUARY', quantity_sold,0)) AS JAN,
sum(if (transaction.month_sold = 'FEBRUARY', quantity_sold, 0)) AS FEB,
sum(if (transaction.month_sold = 'MARCH', quantity_sold, 0)) AS MAR
FROM transaction
JOIN allocations ON allocations.alloc_id = transaction.alloc_id
GROUP BY transaction.month_sold
答案 0 :(得分:-1)
首先,您应该按alloc_id
而不是month_sold
进行分组。
从分配中减去已售出商品的总和,以得出未售出商品。
SELECT allocations.alloc_id,
sum(if (transaction.month_sold = 'JANUARY', quantity_sold,0)) AS JAN,
sum(if (transaction.month_sold = 'FEBRUARY', quantity_sold, 0)) AS FEB,
sum(if (transaction.month_sold = 'MARCH', quantity_sold, 0)) AS MAR,
allocations.item_allocation - SUM(quantity_sold) AS not_sold
FROM transaction
JOIN allocations ON allocations.alloc_id = transaction.alloc_id
GROUP BY allocations.alloc_id