将行转换为列

时间:2015-03-22 18:12:48

标签: sql oracle transpose

我有以下数据

with sample_data as (select to_date('05/01/2015', 'dd/mm/yyyy') dt, '1' Period, 'A' code from dual union all
                 select to_date('05/01/2015', 'dd/mm/yyyy') dt, '2' Period, 'A' code from dual union all
                 select to_date('05/01/2015', 'dd/mm/yyyy') dt, '3' Period, 'P' code from dual union all
                 select to_date('05/01/2015', 'dd/mm/yyyy') dt, '4' Period, 'A' code from dual union all
                 select to_date('05/01/2015', 'dd/mm/yyyy') dt, '5' Period, 'P' code from dual

) select * from sample_data

这给了我简单的查询结果,如下所示

 DT PERIOD  CODE
2015-01-05 00:00:00 1   A
2015-01-05 00:00:00 2   A
2015-01-05 00:00:00 3   P
2015-01-05 00:00:00 4   A
2015-01-09 00:00:00 5   P

我想转发结果 -

DATE           ATTENDANCE
2015-01-05     12345
               AAPAP

我该怎么做? 非常感谢!

1 个答案:

答案 0 :(得分:1)

这是一个Oracle SQL问题,而不是PL / SQL!

这可能是这样的:

select to_char(dt,'YYYY-MM-DD') date,listagg(period) within group (order by period)||chr(13)||chr(10)||listagg(code) within group (order by period) attendance
from (

with sample_data as (select to_date('05/01/2015', 'dd/mm/yyyy') dt, '1' Period, 'A' code from dual union all
             select to_date('05/01/2015', 'dd/mm/yyyy') dt, '2' Period, 'A' code from dual union all
             select to_date('05/01/2015', 'dd/mm/yyyy') dt, '3' Period, 'P' code from dual union all
             select to_date('05/01/2015', 'dd/mm/yyyy') dt, '4' Period, 'A' code from dual union all
             select to_date('05/01/2015', 'dd/mm/yyyy') dt, '5' Period, 'P' code from dual
) select * from sample_data

) group by to_char(dt,'YYYY-MM-DD')

请注意,函数listagg只能在Oracle 11.2中使用。如果您使用的是早期版本,则可以使用xmlagg,但这样会更加凝固。