在mysql中查询2个表,其中包含每月售出商品的摘要,包括未售出的商品

时间:2020-04-17 06:10:05

标签: mysql database

非常需要帮助。所以我有2个表:

  1. 交易
  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

1 个答案:

答案 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