2016-04-08 10 views
1

私は、スキーマを変更することができることを望むが、私はそれに縛らよ、私は以下の表に最初の3つのテーブルが列IDと金額が販売している ピボットMySQLはデータ

JanDataTable 
FebDataTable 
MarDataTable 
ProductsTable 

があるとします。商品表にIDと商品名があります。

私は何とか次の出力

IDは、製品IDです
ID | Product Name | Amount Sold | Month 
01 | TV 1   | 23   | 1  <- JanDataTable 
02 | TV 2   | 43   | 2  <- FebDataTable 
03 | Toaster 1 | 72   | 3  <- MarDataTable 

を取得するために、これらのテーブルを結合する必要があります。

クエリのみ可能ですか?

+0

このデザインは持続不可能です。あなた自身の正気のために、あなたはそれを修正するか、またはこのプロジェクトを放棄することができる位置に自分自身を取得してください。 – Strawberry

答えて

0
select p.product_part,s.* 
from 
(
select d.*, 1 as Month from jandatatable d 
union 
select d.*, 2 as Month from febdatatable d 
union 
select d.*, 3 as Month from mardatatable d 
) s 
join product p on s.Product_id = p.product_id 
order by s.month, p.product_id; 
+0

ありがとう、私はこれに似た – user316114

0

これはいかがですか?

LEFT JOINを使用してください。

select 
    p.id as ID, p.`Product Name`, 
    coalesce(jan.`Amount Sold`,0) + coalesce(feb.`Amount Sold`,0) + coalesce(mar.`Amount Sold`,0) as `Amount Sold`, 
    case when p.id = '01' then 1 
     when p.id = '02' then 2 
     when p.id = '03' thwn 3 
    end as Month 
from ProductsTable as p 
    LEFT JOIN JanDataTable as jan ON p.id = jan.id 
    LEFT JOIN FebDataTable as feb ON p.id = feb.id 
    LEFT JOIN MarDataTable as mar ON p.id = mar.id 
+0

解決策を提供することに決めたら、ここにヒントがあります:UNION – Strawberry