我正在尝试使用以下查询将 Race_code、chara_code 和 reason_code 作为列表检索:

SELECT a.pid,
       LISTAGG(a.rc, ',') WITHIN GROUP (ORDER BY a.rc) AS race,
       LISTAGG(a.cc, ',') WITHIN GROUP (ORDER BY a.cc) as chara_codes,
       LISTAGG(a.rrc, ',') WITHIN GROUP (ORDER BY a.rrc) AS removal_reason
FROM (
   SELECT UNIQUE
          p.person_id pid,
          r.race_code rc,
          c.characteristic_code cc,
          rr.removal_reason_code rrc
     FROM person p left outer join race r on p.person_id = r.person_id
          left outer join characteristic c on p.person_id = c.person_id
          left outer join placement_episode pe on p.person_id = pe.child_id
          left outer join removal_reason rr on pe.placement_episode_id = rr.placement_episode_id
     ) a
GROUP BY a.pid

我在引用了一些链接(如 link1link2 )后尝试了这个查询。但是在这样做之后,我也无法获得所有字段的唯一值。

我的 o/p 是这样的:
pid      race_code     chara_code      reason_code
 1        a,b,b,c     c1,c1,c2,c3     r1,r2,r3,r3
 2       a,c,d,d,d      c1,c2,c2        r3,r3

and so on.

如果我尝试一次只检索一个字段并保留所需的连接操作,那么它会给出正确的结果。但是对于多个 LISTAGG() 函数,它的重复值。
我没有办法做到这一点。有没有其他方法可以获得不同的值?

最佳答案

不幸的是,这比它需要的要复杂得多。但是,你可以做到。这个想法是枚举每个值,然后使用 caseNULL 参数传递给 LISTAGG()

SELECT a.pid,
       LISTAGG(CASE WHEN rc_seqnum = 1 THEN a.rc END, ',') WITHIN GROUP (ORDER BY a.rc) AS race,
       LISTAGG(CASE WHEN cc_seqnum = 1 THEN a.cc END, ',') WITHIN GROUP (ORDER BY a.cc) as chara_codes,
       LISTAGG(CASE WHEN rrc_seqnum = 1 THEN a.rrc END, ',') WITHIN GROUP (ORDER BY a.rrc) AS removal_reason
FROM (SELECT p.person_id as pid, r.race_code as rc, c.characteristic_code as cc,
              rr.removal_reason_code as rrc,
             row_number() over (partition by p.person_id, r.race_code order by r.race_code) as rc_seqnum,
             row_number() over (partition by p.person_id, c.characteristic_code order by c.characteristic_code) as cc_seqnum,
             row_number() over (partition by p.person_id, rr.removal_reason_code order by rr.removal_reason_code) as rrc_seqnum
      FROM person p left outer join race r on p.person_id = r.person_id
           left outer join characteristic c on p.person_id = c.person_id
           left outer join placement_episode pe on p.person_id = pe.child_id
           left outer join removal_reason rr on pe.placement_episode_id = rr.placement_episode_id
     ) a
GROUP BY a.pid;

该查询正在枚举基于每个人和字段组合的行。第一次看到该值时,它的值为“1”,随后的值逐渐增加。 LISTAGG() 只选择第一个值。

您应该了解分析函数。它们非常有用。

关于sql - 如何在选择子句中使用多个 LISTAGG() 函数时选择不同的值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31453882/

10-11 03:37