从2个不同的表中计算(数量*价格)的SUM

时间:2017-02-03 14:15:18

标签: sql postgresql

我有以下2个表,

item_store

item_store table

购买

purchase table

根据brand_id和purchase_time,我想计算销售商品的累计销售额。 在上面的示例场景中,项目'1'已经从商店'1'购买了2次,并且从商店'2'购买了一次。 总销售额应为total_quantity * price =(2 + 5)* 10 + 7 * 12 = 70 + 84 = 154。

我发现以这样的方式加入2个表是很有挑战性的,因为价格来自item_store和 累计数量取自购买表以计算总金额。

这两个表需要根据item_id和store_id以及where子句应该包含的内容进行连接 来自购买表的brand_id和purchase_time(例如 - 其中brand_id = 1且purchase_time> ='2017-02-01 00:00:00.000' 和purchase_time< ='2017-02-10 00:00:00.000')。

截至目前,item_id和brand_id之间总会有一对一的映射。

修改

如果我只想使用购买表中找到的记录数来计算总销售额,而不是在购买表中使用数量列,那么任何想法如何实现它。我的意思是假设购买表中没有数量列,而购买表中的每个条目代表一个销售的商品数量。 所以类似:购买表中的记录的count(*)* item_store中的价格

感谢。

2 个答案:

答案 0 :(得分:3)

我认为这就是你所需要的。这只需要加入表格。

select sum(p.quantity*i.price)
from purchase p
join item_store i on p.item_id=i.item_id and p.store_id=i.store_id
where p.brand_id = 1 
and p.purchase_time >= '2017-02-01 00:00:00.000' 
and p.purchase_time <= '2017-02-10 00:00:00.000'

编辑:基于OP的更新

select count(*) over(partition by p.item_id,p.store_id) * i.price 
from purchase p
join item_store i on p.item_id=i.item_id and p.store_id=i.store_id
where p.brand_id = 1 
and p.purchase_time >= '2017-02-01 00:00:00.000' 
and p.purchase_time <= '2017-02-10 00:00:00.000'

答案 1 :(得分:1)

回答你的第一个问题:

SELECT sum(p.quantity * itm.price) as total
  FROM Item_Store itm
  JOIN Purchase p ON p.store_Id = itm.store_id

要进入问题的第二部分,在那里你谈论表必须使用where where条件抛出你的结果,你可以简单地使用嵌套的select语句 - 然后它对影响的where条件没有区别你的结果。

所以你可以:

原始选择语句 - 类似于:

Select 

column1, column2, etc..., 

(SELECT sum(p.quantity * itm.price) as total
  FROM Item_Store itm
  JOIN Purchase p ON p.store_Id = itm.store_id) as TotalSales

FROM item_store itm
JOIN purchase p ON p.store_Id = itm.store_id
Where brand_id = 1
AND (purchase_time >= '2017-02-01 00:00:00.000' and purchase_time <= '2017-02-10 00:00:00.000')

你甚至可以把它作为一个在线视图连接来实现,我认为它更好,因为它在性能方面更有效,即

Select 

    column1, column2, TotalSales.total, etc...

    FROM item_store itm
    JOIN purchase p ON p.store_Id = itm.store_id
    JOIN (SELECT sum(p.quantity * itm.price) as total
          FROM Item_Store itm2
          JOIN Purchase p2 ON p2.store_Id = itm2.store_id) as TotalSales
    Where brand_id = 1
    AND (purchase_time >= '2017-02-01 00:00:00.000' and purchase_time <= '2017-02-10 00:00:00.000')

您将获得相同的结果,但是连接版本应该更高效,因为它不必为返回的每一行运行sql。

希望有意义!

相关问题