php - Get the top selling product's current inventory in mysql
问题描述
I want to get the top selling product's current inventory from the database. I have successfully fetch the top-selling products but unable to fetch their current inventory in the same query.
SELECT product_name, product_code, SUM(qty) As TotalQuantity FROM `order_items` GROUP BY product_code ORDER BY SUM(qty) DESC LIMIT 5
inventory table is something like that
if you need more info i will update the question.
解决方案
假设表的名称是inventory
。我使用相关子查询来获取当前库存值
SELECT oi.product_name, oi.product_code,
SUM(oi.qty) AS TotalQuantity,
(SELECT SUM(inv.qty) FROM `inventory` AS inv WHERE inv.product_code = oi.product_code) AS CurrentStock
FROM `order_items` AS oi
GROUP BY oi.product_code
ORDER BY TotalQuantity DESC
LIMIT 5
推荐阅读
- python - 在视频流的帧中找到闭合角度的坐标
- mysql - MySQL 8 不检测选择不同查询中的功能依赖关系
- google-maps - 我有以下代码,它说无法解析符号 mMap()。我该怎么办?
- sql - 加入 ( {} ) 2 个单独工作的查询会产生值错误
- javascript - 为大量简单形状设置动画
- android-studio - Gradle 同步失败:找不到方法实现()
- java - java中的多态行为
- python - 如何将单词列表与字典项匹配并返回python中的键?
- spring - 错误以 java.lang.ClassNotFoundException: Spring boot 中的 org.apache.tools.ant.Project 出现
- machine-learning - cross_val_score 与另一种计算精度的方法之间的区别