需要帮助分组行

时间:2012-05-04 09:20:11

标签: sql oracle plsql aggregate-functions string-aggregation

  

可能重复:
  How can I combine multiple rows into a comma-delimited list in Oracle?

我有一个以下列方式存储数据的表 -

60333,120102,20120502,010000,1,2

60333,120102,20120502,020000,3,4 

60333,120102,20120502,030000,5,6 

60333,120102,20120502,040000,7,8 

61663,120103,20120502,010000,9,10 

61663,120103,20120502,020000,11,12 

61663,120103,20120502,030000,13,14 

61663,120103,20120502,040000,15,16 

60333,120102,20120503,010000,17,18 

60333,120102,20120503,020000,19,20 

60333,120102,20120503,030000,21,22 

60333,120102,20120503,040000,23,24 

我希望显示如下输出:

60333,120102,20120502,1,2,3,4,5,6,7,8

60333,120102,20120503,17,18,19,20,21,22,23,24

61663,120103,20120502,,9,10,11,12,13,14 ,15,16

对于唯一的60333,120102和日期,所有数据都需要显示在一行而不是4行。

2 个答案:

答案 0 :(得分:1)

试试这个:

select a, b, c, listagg(e || ',' || f, ',') WITHIN GROUP (ORDER BY e) as x
from tbl
group by a, b, c

实时测试:http://www.sqlfiddle.com/#!4/40a4b/13

答案 1 :(得分:0)

如果我们假设:

  1. 第4列只能使用4个值(010000,020000,030000,040000)和
  2. 您希望输出中始终有11列
  3. 然后你需要"pivot query",就像这样:

    select c1, c2, c3, 
        max(decode(c4, '010000', c5)) as c5for010000,
        max(decode(c4, '010000', c6)) as c6for010000,
        max(decode(c4, '020000', c5)) as c5for020000,
        max(decode(c4, '020000', c6)) as c6for020000,
        max(decode(c4, '030000', c5)) as c5for030000,
        max(decode(c4, '030000', c6)) as c6for030000,
        max(decode(c4, '040000', c5)) as c5for040000,
        max(decode(c4, '040000', c6)) as c6for040000
    my_table
    group by c1, c2, c3;