SQL 查询将 Oracle 中多行的列值与计数连接起来

问题描述 投票:0回答:1

我有以下预言表:

Table A

PID   SEQ    Desc

A     1      Have
A     2      a nice
A     3      day.
B     1      Nice Work.
C     1      Yes
C     2      we can 
C     3      do 
C     4      this work!

我想聚合表的输出,使其应该是 -

PID   Desc1                          Desc2
A     Have a nice day.               Have
A     Have a nice day.               a nice
A     Have a nice day.               day!
B     Nice Work.                     Nice Work.
C     Yes we can do this work!       Yes
C     Yes we can do this work!       we can
C     Yes we can do this work!       do
C     Yes we can do this work!       this work!

注意 SEQ 列决定 desc 聚合的顺序。我尝试过以下查询:

SELECT pid, LISTAGG(Desc, ' ') WITHIN GROUP (ORDER BY seq) AS description
FROM B GROUP BY pid;

这给了我这个结果:

PID   Desc
A     Have a nice day.
B     Nice Work.
C     Yes we can do this work!

我不知道如何获得想要的结果。救命!

oracle aggregate-functions
1个回答
0
投票

您想要的是重复返回的行与表中存在的行一样多

a
。为此,只需将表
a
与您当前拥有的子查询应用交叉连接,例如

WITH bb AS
(
  SELECT pid, LISTAGG("Desc", ' ') WITHIN GROUP ( ORDER BY seq ) AS desc1
    FROM b
   GROUP BY pid
)
SELECT a.pid, bb.pid, "Desc" AS desc2
  FROM a
 CROSS JOIN bb
© www.soinside.com 2019 - 2024. All rights reserved.