如何从以下sql表中获取mysql中产品的总成本?

时间:2014-04-20 09:40:25

标签: mysql database

如何从下表中计算产品的总成本? 表1:组件

 pk_comp_id     comp_name           fk_comp_type_id  com_price
        1           Vertical Glass Panels   3               50.00
        2           Side Frame              2               32.00
        3           Front Frame             2               35.00
        4           Roof Section            3               50.00
        5           Door Frame              1               100.00
        6           Standard Timber Plank   2               100.00
        7           Brackets                6               20.00
        8           Door Section            2               50.00

表2:产品

 pk_prod_id  prod_name         fk_prod_type_id
    1       Small Green House   1
    2       Large Green House   1
    3       Small Shed          2
    4       Small Summer House  3
    5       Large Summer House  3

表3:products_components

fk_prod_id  fk_comp_id  number
    1           1       20
    1           2       2
    1           3       2
    1           4       2
    1           5       1
    2           1       40
    2           2       4
    2           3       2
    2           4       4
    2           5       1
    3           6       35
    3           7       60
    3           8       1

这是我到目前为止所做的事情

SELECT 
SUM(`components`.`com_price`*`products_components`.`number`) AS com_g_total,
`products`.`prod_name`, `products`.`pk_prod_id`
FROM `products`
INNER JOIN `products_components` ON `products_components`.`fk_prod_id` = `products`.`pk_prod_id`
INNER JOIN `components` ON `components`.`pk_comp_id` = `products_components`.`fk_comp_id`

但是这只给出了一行,因为我想要获得三行,每行的总成本为pk_prod_id 1,2,3。

1 个答案:

答案 0 :(得分:0)

添加GROUP BY子句:

SELECT 
SUM(`components`.`com_price`*`products_components`.`number`) AS com_g_total,
`products`.`prod_name`, `products`.`pk_prod_id`
FROM `products`
INNER JOIN `products_components` ON `products_components`.`fk_prod_id` = `products`.`pk_prod_id`
INNER JOIN `components` ON `components`.`pk_comp_id` = `products_components`.`fk_comp_id`
GROUP BY `products`.`pk_prod_id`

结果:

COM_G_TOTAL   PROD_NAME            PK_PROD_ID
1334          Small Green House    1
2498          Large Green House    2
4750          Small Shed           3

请参阅SQL Fiddle中的结果。