2015-10-16 123 views
0

列我有一个表包含材料类型:的Oracle SQL斯普利特型

id type mat_number description  count 
------------------------------------------------ 
a mat_1 123456  wood type a  5 
a mat_2 333333  plastic type a  8 
b mat_1 654321  wood type b  7 
c mat_2 444444  plastic type c 11 
d mat_1 121212  wood type z  8 
d mat_2 444444  plastic type c  2 
d mat_2 555555  plastic type d  3 

与SQL我想如下创建列表:

id mat_1  desciption  count mat_2  description  count 
------------------------------------------------------------------- 
a 123456 wood type a  5  333333 plastic type c 8 
b 654321 wood type b  7  null 
c null        444444 plastic type c 11 
d 121212 plastic type c 8  444444 plastic type c 2 
d null        555555 plastic type c 3 

这有可能与没有太多精力?

+0

你的努力如何? – Mihai

+0

根据你想要哪条规则获得'd'的行?为什么'121212 444444',但对于第二个mat_2,你有null null 555555?为什么不以'121212 444444','121212 555555'为例? – Tatiana

+0

,因为这是客户的要求。 – user

回答

2

如果你首先是计算每个ID和类型分组行号,然后旋转很简单:

with sample_data as (select 'a' id, 'mat_1' type, 123456 mat_number from dual union all 
        select 'a' id, 'mat_2' type, 333333 mat_number from dual union all 
        select 'b' id, 'mat_1' type, 654321 mat_number from dual union all 
        select 'c' id, 'mat_2' type, 444444 mat_number from dual union all 
        select 'd' id, 'mat_1' type, 121212 mat_number from dual union all 
        select 'd' id, 'mat_2' type, 444444 mat_number from dual union all 
        select 'd' id, 'mat_2' type, 555555 mat_number from dual) 
select id, 
     mat_1, 
     mat_2 
from (select id, 
       type, 
       mat_number, 
       row_number() over (partition by id, type order by mat_number) rn 
     from sample_data) 
pivot (max(mat_number) 
     for (type) in ('mat_1' as mat_1, 'mat_2' as mat_2)) 
order by id, rn; 

ID  MAT_1  MAT_2 
-- ---------- ---------- 
a  123456  333333 
b  654321   
c     444444 
d  121212  444444 
d     555555 
+0

完美!这正是我正在寻找的。非常感谢你。 – user

+0

这也是如何使用枢轴功能的一个很好的例子! –

+0

是否也可以转动完成行? – user

0

我认为你需要一个标准的PIVOT查询。你的输出似乎错了。

例如,

SQL> SELECT * FROM t; 

ID TYPE MAT_NUMBER 
-- ----- ---------- 
a mat_1  123456 
a mat_2  333333 
b mat_1  654321 
c mat_2  444444 
d mat_1  121212 
d mat_2  444444 
d mat_2  555555 

7 rows selected. 

PIVOT查询

SQL> SELECT * 
    2 FROM (SELECT id, mat_number, type 
    3   FROM t) 
    4 PIVOT (MAX(mat_number) AS mat FOR (TYPE) IN ('mat_1' AS A, 'mat_2' AS b)) 
    5 ORDER BY ID; 

I  A_MAT  B_MAT 
- ---------- ---------- 
a  123456  333333 
b  654321 
c    444444 
d  121212  555555 
+0

在问我的问题之前,我有同样的想法。这是一个非常优雅的方式。但在这里我想念'd'的第二排。 d(null)444444 – user

+0

@user是的,我错过了。您需要在每个ID中对mat_number进行排名。这是骨科医生建议的(我猜)。 –

0

我的查询可以给你ouptut喜欢

Id  mat_number 
- ------------------ 
a  123456,333333 
b  654321 
c  444444 
d  121212,444444,555555 

看到这个查询是否有帮助

select id,rtrim (xmlagg (xmlelement (e,s3.mat_number,',') order by s3.type).extract ('//text()'), ' ,') mat_number 
from t s3 
group by id 
+0

但OP不希望字符串聚合。 –