mysql:如何将乘法部分相加

时间:2013-01-07 20:51:52

标签: mysql sum multiplying

拥有以下表格:

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

这将是您获得的最佳(更快的查询)方法

结果:

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

2 个答案:

答案 0 :(得分:5)

这应该有效:

 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

答案 1 :(得分:3)

请试一试。

代码:

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
;

结果:

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