oracle sql 按类型拆分列

oracle sql split columns by type

我有一个 table 包含 material 类型:

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

不费吹灰之力就可以吗?

我认为您需要一个标准的 PIVOT 查询。不过你的输出似乎有误。

例如,

Table

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

我的查询可以给你输出 luke

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

如果您首先为每个 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