如何将重复的键字段分组并为值创建新列

时间:2018-07-19 04:12:03

标签: sql oracle

目前,我正在使用iReport 3.0.0和Java。 我需要从具有 ID Name 字段的A表与具有 Value 字段的B表联接。

一个ID可以具有多个值。...

我有如下表格;

ID名称名称值
==== ==== ====
ABC 1
ABC 1
BCD BCD 1
CDE CDE 1

我必须将数据读取为:
ID ID名称值
==== ==== ====
A ABC 1,2
BCD BCD 1
CDE CDE 1

要么

ID名称NameValue1 Value2
==== ==== ====
ABC ABC 1 2
BCD BCD 1
CDE CDE 1

是否可以在不使用程序的情况下用sql编写此代码?

预先感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

您可以使用listagg函数-它连接值。

with 
A as (
  select 'A' id, 'ABC' name from dual union all
  select 'B' id, 'BCD' name from dual union all
  select 'C' id, 'CDE' name from dual
),
B as (
  select 'A' id, '1' value from dual union all
  select 'A' id, '2' value from dual union all
  select 'B' id, '1' value from dual union all
  select 'C' id, '1' value from dual
)
select A.id, A.name, 
       listagg(B.value,',') within group (order by B.value) list_of_values
from   A join B on A.id = B.id
group by A.id, A.name

请注意,最长的listagg结果限制为4K个字符。

答案 1 :(得分:0)

尝试以下查询-:

SELECT Distinct id,Name,Value = STUFF(
(
select ',' + cast(row_number() over(partition by A.id,A.name order by value)as varchar(100)) 
from YOURTABLENAME A 
where A.id = B.id FOR XML PATH('')), 1, 1, ''
)
From
(
select  row_number() over(partition by id,name order by value) as r,id,name 
from YOURTABLENAME
)B