mysql - 查询 mysql 以获取 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
解决方案
首先,您应该按 分组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
推荐阅读
- api - 为什么“服务器上的 IIS”的行为与“本地 IIS”和“IIS Express”的行为不同?(ASP.NET Core + Angular + Windows 身份验证)
- html - 如何在 Google 网站上为 Google 表格创建外部参考页面
- cng - 未找到加密提供程序开发工具包
- reactjs - Jotai + React:意外的重新渲染和意外的陈旧状态值
- html - 当我将边栏中的内容设置为显示时,它不再随浏览器窗口一起缩小:grid
- java - 控制台整体执行程序的问题
- c++ - for 循环条件 (str1[i] && str2[i]) 是什么意思?
- jenkins - 在 Clearcase 中使用 Jenkins 创建分支和配置文件
- javascript - 使用组件反应 Typescript 自动完成
- rxjs - 关于 2 个 rxjs 可观察对象和一个计时器的问题