mysql: how to sum multiplied partials

南楼画角 提交于 2019-12-01 18:14:24

问题


Having tables like:

sold_items:

code   | size   | quantity 
abc123 | small  | 4
abc123 | medium | 2  
xyz987 | small  | 3
xyz987 | medium | 1
xyz987 | large  | 2

price_list:

code   | size   | price 
abc123 | small  | 5
abc123 | medium | 7  
abc123 | large  | 9 
xyz987 | small  | 10
xyz987 | medium | 13
xyz987 | large  | 15

which would be your best (faster query) approach to get

results:

code   | sold_items | cash
abc123 | 6          | 34
xyz987 | 6          | 73

回答1:


This should work:

 SELECT si.code, SUM(si.quantity), SUM(si.quantity * pl.price) as cash
 FROM sold_items si
 INNER JOIN price_list pl ON pl.code = si.code AND pl.size = si.size
 GROUP BY si.code



回答2:


Try this out please.

  • SQLFIDDLE DEMO

Code:

select p.code, sum(p.quantity), sum(q.quantity * p.price)
from prc p
inner join 
qty q
on p.code = q.code
and p.size = q.size
group by p.code
;

Results:

CODE    SUM(Q.QUANTITY)     SUM(Q.QUANTITY * P.PRICE)
abc123      6                   34
xyz987      6                   73


来源:https://stackoverflow.com/questions/14203821/mysql-how-to-sum-multiplied-partials

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!