2017-02-24 107 views
1

我有那些给表:结合两个表的SQL

enter image description here

表2中可以多行的“Kost_ID”,在输出这些“Kost_ID”应该是只有一行。 “MW_ID”应为结果“MW”+数字(此处为“MW5”,“MW6”为“MW_ID”5 + 6)。希望这已经够清楚了。

我怎么能在oracle数据库中使用sql?感谢

表1

ID Kost_ID Col1 
2016 1 bla 
2016 2 bla 
2016 3 bla1 
2016 4 abl 
2016 5 
2016 6 
2016 7 
2017 2 
2017 3 

Table2   

ID Kost_ID MW_ID Euro 
2016 1 1 10 
2016 2 2 20 
2016 3 6 30 
2016 3 5 40 
2016 5 5 50 
2016 6 6 60 
2016 7 3 70 
2016 4 4 80 

Result:        

ID Kost_ID Col1 MW1 MW2 MW3 MW4 MW5 MW6 
2016 1 bla 10     
2016 2 bla  20    
2016 3 bla1     40 30 
2016 4 abl    80  
2016 5      50 
2016 6       60 
2016 7    70  
+1

请后的数据作为格式化的文本,[不是截图](http://meta.stackove rflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question/285557#285557)。我知道颜色在这里可能很有用,但是如果您可以发布相同数据的文本版本,那么这对于人们构建示例并尝试一些内容会很有用。 – Aleksej

+0

MW_ID是否有最大值?或者你想让结果表展开未知数量的列? –

+0

@MihaiOvidiuDrăgoi最大值是6 –

回答

1

对于评论提到completness枢轴溶液:

select * 
    from table1 join table2 using (id, kost_id) 
    pivot (sum(euro) for mw_id in (1 mw1, 2 mw2, 3 mw3, 4 mw4, 5 mw5, 6 mw6)) 
    order by id 

Test example

(抱歉延迟)

2

如果你不希望使用数据透视查询你可以用左联接,也许有点无聊,手工老风格

select t1.*, 
t21.euro mw1,t22.euro mw2, t23.euro mw3,t24.euro mw4,t25.euro mw5,t26.euro mw6 
from 
table1 t1 left join table2 t21 
on t1.id=t21.id 
and t1.kost_id=t21.kost_id 
and t21.mw_id=1 
left join table2 t22 
on t1.id=t22.id 
and t1.kost_id=t22.kost_id 
and t22.mw_id=2 
left join table2 t23 
on t1.id=t23.id 
and t1.kost_id=t23.kost_id 
and t23.mw_id=3 
left join table2 t24 
on t1.id=t24.id 
and t1.kost_id=t24.kost_id 
and t24.mw_id=4 
left join table2 t25 
on t1.id=t25.id 
and t1.kost_id=t25.kost_id 
and t25.mw_id=5 
left join table2 t26 
on t1.id=t26.id 
and t1.kost_id=t26.kost_id 
and t26.mw_id=6 


order by t1.id, t1.kost_id 
1

我差点尝试,但它需要一些改进。

select a.ID, a.Kost_ID,a.Col1, 
case b.MW_ID when 1 then b.Euro else null end MW1, 
case b.MW_ID when 2 then b.Euro else null end MW2, 
case b.MW_ID when 3 then b.Euro else null end MW3, 
case b.MW_ID when 4 then b.Euro else null end MW4, 
case b.MW_ID when 5 then b.Euro else null end MW5, 
case b.MW_ID when 6 then b.Euro else null end MW6 
from table1 a join table2 b 
on (a.ID=b.ID and a.Kost_ID=b.Kost_ID) 

ID Kost_ID Col1 MW1  MW2  MW3  MW4  MW5  MW6 
2016 1 bla  10  NULL NULL NULL NULL NULL 
2016 2 bla  NULL 20  NULL NULL NULL NULL 
2016 3 bla1 NULL NULL NULL NULL NULL 30 
2016 3 bla1 NULL NULL NULL NULL 40  NULL 
2016 4 abl  NULL NULL NULL 80  NULL NULL 
2016 5 NULL NULL NULL NULL NULL 50  NULL 
2016 6 NULL NULL NULL NULL NULL NULL 60 
2016 7 NULL NULL NULL 70  NULL NULL NULL