3

我不确定之前是否在其他任何地方问过这个问题。我也不知道该怎么说。但我会用一个场景来解释。
我有以下表格
TAB1 与列:USERID、CODE、COUNTRY
TAB2 与列:USERID、CODE、EMAIL

示例内容:

TAB1:
RISHI, A1B2C3, INDIA
RISHI, D2E3F4, INDIA
KANTA, G3H4I5, INDONESIA

TAB2:
RISHI, A1B2C3, rishi1@test.com
RISHI, A1B2C3, rishi2@test.com
RISHI, A1B2C3, rishi3@test.com
RISHI, D2E3F4, rishi1@test.com
RISHI, D2E3F4, rishi2@test.com
KANTA, G3H4I5, kanta1@test.com

我从选择查询或 pl/sql 存储过程中想要的是这样的结果:

RISHI, INDIA, A1B2C3, (rishi1@test.com, rishi2@test.com, rishi3@test.com)
RISHI, INDIA, D2E3F4, (rishi1@test.com, rishi2@test.com)

如果我选择如下:

select a.userid, a.code, a.country, b.email
from tab1.a, tab2.b
where a.userid = b.userid
and a.code = b.code
and a.userid = 'RISHI';

我得到的结果是:

RISHI, INDIA, A1B2C3, rishi1@test.com
RISHI, INDIA, A1B2C3, rishi2@test.com
RISHI, INDIA, A1B2C3, rishi3@test.com
RISHI, INDIA, D2E3F4, rishi1@test.com
RISHI, INDIA, D2E3F4, rishi2@test.com

我基本上需要的是组合成一个数组的电子邮件 ID。假设 TAB1 包含更多我实际需要但我在此示例中省略的列,但 TAB2 只有这三列。

4

2 回答 2

2
select a.userid, a.code, a.country, listagg(b.email, ',') within group (order by b.email) as "Emails"
from tab1.a, tab2.b
where a.userid = b.userid
and a.code = b.code
and a.userid = 'RISHI'
group by a.userid, a.code, a.country;
于 2012-02-03T13:09:09.870 回答
0

我想你想GROUP_CONCAT在 MySQL 中使用聚合函数。坏消息是 Oracle 没有内置的组连接功能,好消息是您可以模拟这样的功能。

看看这个片段:

with data
     as
     (
          select job,
                ename,
                row_number() over (partition by job order by ename) rn,
                count(*) over (partition by job) cnt
      from emp
     )
 select job, ltrim(sys_connect_by_path(ename,','),',') scbp
  from data
  where rn = cnt
  start with rn = 1
  connect by prior job = job and prior rn = rn-1
  order by job

并将返回

JOB       SCBP
--------- ----------------------------------------
ANALYST   FORD,SCOTT
CLERK     ADAMS,JAMES,MILLER,SMITH
MANAGER   BLAKE,CLARK,JONES
PRESIDENT KING
SALESMAN  ALLEN,MARTIN,TURNER,WARD

参考

于 2012-02-03T13:01:45.953 回答