MySQL:合并2个表并计算总和值

时间:2014-04-10 13:48:19

标签: mysql sql

如何合并booksales_itemsum(total_price)计算isbn组(result之类的输出)。 THX〜

book
-----------------------------------------------------------
isbn   title    price
111    AAA      100     
222    BBB      90 
333    CCC      150

sales_item
-----------------------------------------------------------
bill_id  isbn  quantity  price    total_price
1        111   5         100      500
1        222   1         90       90
2        333   1         150      150
3        111   8         100      800



result
-----------------------------------------------------------
isbn   title   price  sum(total_price)
111    AAA     100    1300
222    BBB     90     90
333    CCC     150    150

2 个答案:

答案 0 :(得分:0)

试试吗?

select si.isbn, 
 MAX(b.title) as title, 
 MAX(b.price) as price, 
 sum(si.total_price) as total_price
From book b
inner join sales_item si on b.isbn = b.isbn
Group by si.isbn

答案 1 :(得分:0)

简单地按isbn分组:

SELECT book.isbn, book.title, book.price, SUM(total_price) 
FROM sales_item, book 
WHERE book.isbn = sales_item.isbn GROUP BY isbn;