我需要帮助以下正在处理的程序。 我有两个表inventory_list表和Sales_Report表,我试图计算在Sales_Report表中进行销售后在inventory_list中剩下的项目。
表格如下:
InventoryList表
ProductName Quantity
Dell Laptops 12
Wrist Watches 6
Lenovo Laptops 5
Dell Laptops 4
Wrist Watches 3
HP Laptops 15
SalesReport表
ProductName Quantity
Dell Laptops 1
Wrist Watches 2
Lenovo Laptops 1
Dell Laptops 1
Wrist Watches 1
我写了下面的查询,但它给了我错误的数字, 我们的想法是让查询添加具有相同名称的产品,并在销售时减去。
select i.ProductName,
(sum(i.Quantity - r.Quantity)) AS number_items_left
from InventoryList i
JOIN Report_details r ON i.ProductName = r.ProductName
GROUP BY i.ProductName, r.ProductName
预期结果应该是。 ProductName number_items_left 戴尔笔记本电脑14 联想笔记本电脑4 手表6
答案 0 :(得分:1)
请尝试以下方法,而不是您的查询:
select i.ProductName,
i.sum - COALESCE(r.sum,0) AS number_items_left
from (SELECT
i.ProductName,
sum(i.Quantity) as sum
FROM InventoryList i
GROUP BY i.ProductName) i
LEFT JOIN (SELECT
r.ProductName,
sum(r.Quantity) as sum
FROM Report_details r
GROUP BY r.ProductName) r
ON i.ProductName = r.ProductName
Explenation:在您的查询中,您要加入ProductName
列 DUPLICATING 数据。这就是问题所在。
答案 1 :(得分:0)
您需要先对各个表进行求和。因为在汇总之前你有重复的数据和连接表会创建交叉连接。这是更新版本。
create table InventoryList (ProductName nvarchar(50), Quantity int)
create table SalesReport (ProductName nvarchar(50), Quantity int)
insert into InventoryList values
('Dell Laptops',12),
('Wrist Watches',6),
('Lenovo Laptops',5),
('Dell Laptops',4),
('Wrist Watches',3),
('HP Laptops',15)
insert into SalesReport values
('Dell Laptops',1),
('Wrist Watches',2),
('Lenovo Laptops',1),
('Dell Laptops',1),
('Wrist Watches',1)
select i.ProductName, i.sumQuantity, s.sumQuantity, i.sumQuantity - COALESCE(s.sumQuantity,0) as inventory
FROM
(
select ProductName,sum(Quantity) as sumQuantity
from InventoryList
GROUP BY ProductName
) i
LEFT JOIN
(
select ProductName,sum(Quantity) as sumQuantity
from SalesReport
GROUP BY ProductName
) s
on
i.ProductName = s.ProductName
此查询的结果是
ProductName sumQuantity sumQuantity inventory
Dell Laptops 16 2 14
HP Laptops 15 NULL 15
Lenovo Laptops 5 1 4
Wrist Watches 9 3 6
答案 2 :(得分:0)
WITH stock AS (
SELECT productname, sum(quantity) AS stock
FROM inventory
GROUP BY productname
)
SELECT productname, stock - sum(r.quantity) AS number_items_left
FROM report_details r
JOIN stock USING (productname)
GROUP BY productname, stock
编辑:如果有些产品没有销售,你应该对库存进行正确的加入。