【问题标题】:SQL Query to concatenate column values from multiple rows in Oracle 11g version 1.1 [duplicate]用于连接 Oracle 11g 版本 1.1 中多行的列值的 SQL 查询 [重复]
【发布时间】:2014-01-02 04:54:18
【问题描述】:

是否可以在 Oracle 11g 版本 1.1 中构造 SQL 来连接多行的列值?

以下是一个例子:

Table A

dName cName amount  type
  A     B     100   water
  A     B     200   house
  A     C     400   air
  A     B     300   water

SQL 的输出应该是 -

dName   CName  totalAmount  count      type
A        B       600         3     water,house
A        C       400         1         air       

删除重复类型也不同..

所以基本上输出结果的类型列是表 A 中的类型值与 dName 和 cName 的 sum(amount) 组的串联。

对 SQL 有帮助吗?我正在使用 Oracle 11g 1.1 版。所以 listagg() 函数不起作用。实际上我不想使用 collect() 函数。我的意思是不需要改变当前的表结构。

【问题讨论】:

    标签: sql oracle oracle11g string-concatenation


    【解决方案1】:

    你可以试试wm_concat(),一个不支持的功能:

    select dName, CName, totalAmount, "count", wm_concat("type") as "type"
    from a
    group by dName, CName, totalAmount, "count";
    

    Here 是关于在 Oracle 中完成此任务的许多其他方法的一个很好的资源。

    编辑:

    如果您不想编写自己的函数并且只有少量的东西要放在一起,您可以使用条件聚合方法:

    select dName, CName, totalAmount, "count",
           (max(case when seqnum = 1 then "type" end) ||
            max(case when seqnum = 2 then ','||"type" end) ||
            max(case when seqnum = 3 then ','||"type" end) ||
            max(case when seqnum = 4 then ','||"type" end) ||
            max(case when seqnum = 5 then ','||"type" end)
           ) as "type"
    from (select a.*,
                 row_number() over (partition by dName, CName, totalAmount, "count"
                                    order by "type"
                                   ) as seqnum
         ) a
    group by dName, CName, totalAmount, "count";
    

    【讨论】:

    • 11.1 上午使用。不支持 wm_concat
    【解决方案2】:

    在 oracle 11g 中尝试这个查询:

    select t1.dName,t1.CName,t2.TotalAmount,t2.count,t1.type from
    (select dName,CName,LISTAGG(TYPE,',') within group(order by TYPE)as type
    from
    (select UNIQUE dName,CName,type from A)
    group by dName, CName)t1,
    (select dName,CName,sum(amount) as TotalAmount,count(amount) as count
    from A group by dName, CName)t2
    where t1.dName||t1.CName = t2.dName||t2.CName order by CName;
    

    如果你不能使用 listagg 试试这个查询:

    select t1.dName,t1.CName,t2.TotalAmount,t2.count,t1.type from
    (select dName,CName,rtrim (xmlagg (xmlelement(e,TYPE||',')).extract ('//text()'), ',')  as type
    from
    (select UNIQUE dName,CName,type from A)
    group by dName, CName)t1,
    (select dName,CName,sum(amount) as TotalAmount,count(amount) as count
    from A group by dName, CName)t2
    where t1.dName||t1.CName = t2.dName||t2.CName order by CName;
    

    【讨论】:

      猜你喜欢
      • 2011-06-08
      • 1970-01-01
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      • 2012-08-23
      • 1970-01-01
      • 2023-03-14
      • 2011-10-07
      相关资源
      最近更新 更多