计算不同表格中的产品和总价

时间:2011-05-17 10:36:29

标签: mysql select count sum

我有这三个表:

Products
ID      NAME
1       Notebook
2       Keyboard

Base1
PRODUCT_ID    PRICE
1             2
1             2
1             2
2             3

Base2
PRODUCT_ID    PRICE
1             2
1             2
1             2
1             2
2             3
2             3  

我需要的是获得所有具有出现次数和总和过程的产品列表,如下所示:

ID     NAME       Base1_count  Base1_SumPrice     Base2_count  Base2_SumPrice
1      Notebook   3            6                  4            8
2      Keyboard   1            3                  2            6

如何编写正确的MySQL查询?

2 个答案:

答案 0 :(得分:2)

嘿你可以通过以下查询获得答案

SELECT product_base1.product_id ID
, product_base1.product_name NAME
, product_base1.base1_count Base1_count
, product_base1.base1_price Base1_SumPrice
, COUNT(b2.id) Base2_count
, SUM(b2.price) Base2_SumPrice
FROM ( 
SELECT p.id product_id 
        , p.name product_name
        , COUNT(b.id) base1_count
        , SUM(b.price) base1_price
FROM products p
LEFT OUTER
JOIN base1 b ON p.id = b.id
GROUP BY p.id 
    ) 
    product_base1
LEFT OUTER
JOIN base2 b2 ON b2.id = product_base1.product_id
GROUP BY product_base1.product_id

答案 1 :(得分:0)

SELECT p.ID, p.NAME,
     sum(CASE WHEN b.Base_Name = 'Base1' THEN 1 ELSE 0 END) Base1_count,
     sum(CASE WHEN b.Base_Name = 'Base1' THEN b.PRICE ELSE 0 END) Base1_SumPrice,
     sum(CASE WHEN b.Base_Name = 'Base2' THEN 1 ELSE 0 END) Base1_count,
     sum(CASE WHEN b.Base_Name = 'Base2' THEN b.PRICE ELSE 0 END) Base1_SumPrice
  FROM Products p
  LEFT JOIN (SELECT 'Base1' Base_Name, b1.*
             UNION ALL
             SELECT 'Base2' Base_Name, b2.*) b
         ON p.ID=b.PRODUCT_ID
GROUP BY p.ID, p.Name