2016-09-07 14 views
0

私はmysql上でビューを作成しています。 私が持っている3表:特定の条件を持つVIEW SQLの3つのテーブルからのJOINとSUM

price_list

+----------+-----------+ 
| id_price | price_name| 
+----------+-----------+ 
| 11  | retail | 
| 12  | agen  | 
| 13  | subagen | 
| 14  | distro | 
+----------+-----------+ 

basic_price

+------------+-------------+ 
| id_product | basic_price | 
+------------+-------------+ 
| 1001  | 1000  | 
| 1002  | 2000  | 
| 1003  | 3000  | 
| 1004  | 4000  | 
+------------+-------------+ 

今margin_price

+----------+------------+-------------+ 
| id_price | id_product | margin_price| 
+----------+------------+-------------+ 
| 11  | 1001  | 100   | 
| 12  | 1001  | 200   | 
| 13  | 1001  | 300   | 
| 14  | 1001  | 400   | 
| 11  | 1002  | 200   | 
| 12  | 1002  | 300   | 
| 13  | 1002  | 400   | 
| 14  | 1002  | 500   | 
| 11  | 1003  | 300   | 
| 12  | 1003  | 400   | 
| 13  | 1003  | 500   | 
| 14  | 1003  | 600   | 
| 11  | 1004  | 400   | 
| 12  | 1004  | 500   | 
| 13  | 1004  | 600   | 
| 14  | 1004  | 700   | 
+----------+------------+-------------+ 

が、私はVIEWを作成し、margin_price列を持つbasic_price列を合計しますこれは次のようになります。

+----------+-----------+------------+----------+-------------+------------+ 
|id_product|basic_price|retail_price|agen_price|subagen_price|distro_price| 
+----------+-----------+------------+----------+-------------+------------+ 
| 1001  | 1000  | 1100  | 1200  | 1300  | 1400  | 
| 1002  | 2000  | 2200  | 2300  | 2400  | 2500  | 
| 1003  | 3000  | 3300  | 3400  | 3500  | 3600  | 
| 1004  | 4000  | 4400  | 4500  | 4600  | 4700  | 
+----------+-----------+------------+----------+-------------+------------+ 

この問題を解決するにはどうすればよいですか?

+0

どこretail_price、agen_price、subagen_price、distro_priceがありますか? – Backtrack

答えて

1
select 
    bp.id_product, 
    bp.basic_price, 
    SUM(CASE 
     WHEN pl.price_name='retail' THEN mp.margin_price ELSE 0 
     END) as retail_price 
    SUM(CASE 
     WHEN pl.price_name='agen' THEN mp.margin_price ELSE 0 
     END) as agen_price, 
    SUM(CASE 
     WHEN pl.price_name='subagen' THEN mp.margin_price ELSE 0 
     END) as subagen_price, 
    SUM(CASE 
     WHEN pl.price_name='distro' THEN mp.margin_price ELSE 0 
     END) as distro_price 
from basic_price bp 
    join margin_price mp on bp.id_product=mp.id_product 
    join price_list pl on mp.id_price =pl.id_price 
GROUP by bp.id_product 
0
SELECT 
    A.id_product, 
    A.basic_price, 
    SUM(CASE WHEN C.id_price = 11 THEN A.basic_price + B.margin_price ELSE 0 END) AS retail_price, 
    SUM(CASE WHEN C.id_price = 12 THEN A.basic_price + B.margin_price ELSE 0 END) AS agen_price, 
    SUM(CASE WHEN C.id_price = 13 THEN A.basic_price + B.margin_price ELSE 0 END) AS subagen_price, 
    SUM(CASE WHEN C.id_price = 14 THEN A.basic_price + B.margin_price ELSE 0 END) AS distro_price 
    FROM basic_price A 
    JOIN margin_price B ON A.id_product = B.id_product 
    JOIN price_list C ON C.id_price = B.id_price 
    GROUP BY A.id_product, A.basic_price 
関連する問題