我试图从一张表中按周计算单位销售额并乘以另一张表中的定价并按产品获得结果。我用了this Stack Overflow post。结果恰好是他们应该的两倍。
查询如下:
SELECT product, week, SUM(units * price) AS revenue
FROM weekly_sales
JOIN pricing ON
weekly_sales.product = pricing.product
GROUP BY product, week;
我尝试了一些像使用DISTINCT的东西。最初正在进行第二次加入以获取目录信息,但删除了以确保不是问题。我还使用了WHERE week = current.week,看看我是否可以让它工作一周,但同样的问题。谢谢!
weekly_sales看起来像:
product | units | week
B001 | 5 | 41
B001 | 2 | 42
B002 | 3 | 41
B002 | 8 | 42
定价表如下:
product | current_price | week
B001 | 6.99 | 41
B002 | 8.99 | 41
结果如下:
product | week | revenue
B001 | 42 | 69.9
B001 | 41 | 27.96
B002 | 42 | 53.94
答案 0 :(得分:3)
我认为你应该在join中再添加一个条件,如下所示:
SELECT product, week, (units * price) AS revenue
FROM weekly_sales
JOIN pricing ON
weekly_sales.product = pricing.product
and weekly_sales.week = pricing.week
GROUP BY 1, 2;
希望它有所帮助!