首页 > 解决方案 > 查询 mysql 以获取 2 个表,其中包含每月已售商品的摘要,包括未售出的商品

问题描述

寻求帮助,太糟糕了。所以我有两张桌子:

  1. 交易
  2. 分配

我的事务表包含这些 ff。列:

transaction_id(int)、alloc_id(int)、month_sold(varchar)、quantity_sold(int)

我的分配表包含这些 ff。列:

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

标签: mysqldatabase

解决方案


首先,您应该按 分组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

推荐阅读