获取随价格变化而售出的商品的总价和数量

Get total price and quantity of items sold with price changes

我有这些 table:

PriceChanges table 跟踪每个项目的价格变化。
我想获得两个日期之间售出的商品以及每个商品的总收入(价格*数量),而数量是在此期间以相同价格售出的商品的总数(没有商品的价格变化)。
这意味着每当价格发生变化时,我都会得到一个新行,其中包含以新价格售出的商品总数。
这是所需输出的示例:

id 名称 总售价
------ ------ ----- ------ ------
8P01 51645A 3 1,20 3,60
8P01 51645A 1 2,82 2,82
8P01 51645A 5 2,50 12,50

我试过这个 SQL 命令,但我无法停止获得太多重复的行:

SELECT
i.id,  
i.name,
sum(rc.assigned_quantity) AS assigned_quantity,
pc.price,
pc.price * sum(rc.assigned_quantity) as total 
FROM requested_category rc 
LEFT JOIN items i ON rc.item_id = i.id 
LEFT JOIN request r ON rc.request_id = r.id 
LEFT JOIN priceChanges pc ON pc.item_id = i.id
WHERE
r.delivery_date BETWEEN 'startDate' AND 'endDate' 
GROUP BY i.id, i.name, pc.price

我得到的结果:

id 名称 总售价
------ ------ ----- ------ ------
8P01 51645A 3 1,20 3,60
8P01 51645A 1 1,20 1,20
8P01 51645A 5 1,20 6,00
8P01 51645A 3 2,82 7,86
8P01 51645A 1 2,82 2,82
8P01 51645A 5 2,82 12,10
8P01 51645A 3 2,50 7,50
8P01 51645A 1 2,50 2,50
8P01 51645A 5 2,50 12,50

我按照下面的评论中的要求尝试了以下查询:

SELECT i.id, i.name, rc.assigned_quantity, pc.price
FROM requested_category rc 
LEFT JOIN items i ON rc.item_id = i.id 
LEFT JOIN request r ON rc.request_id = r.id 
LEFT JOIN priceChanges pc ON pc.item_id = i.id 
WHERE r.delivery_date BETWEEN 'startDate' AND 'endDate'

我得到这个结果:

 id 名称 assigned_quantity 价格
8P01 51645A 1 1.20
8P01 51645A 1 2.82
8P01 51645A 1 2.50
8P01 51645A 3 1.20
8P01 51645A 3 2.82
8P01 51645A 3 2.50
8P01 51645A 5 1.20
8P01 51645A 5 2.82
8P01 51645A 5 2.50

谢谢

我带着我用过的解决方案回来了。
在我的应用程序中,我使用 Symfony Framewok 和 Doctine Framework 来处理数据库。

我不是 DBAdmin,但我认为这个解决方案也可以通过数据库触发器来实现。在这种情况下,我选择了 applicatif 方法,因为我使用了 Top-Down design.

需求背后的业务逻辑是尝试获取商店输出报告(商品*每期价格),因为价格在商品进口时是固定的。

我使用 Entity Listener 监视商品价格的任何变化。每当有变化时,我都会记录(价格、数量、开始日期、结束日期)
当生成报告时,我只需将时间段与商品价格变化相匹配,并将其乘以同一数据库条目中记录的数量。

希望我帮助了某人。