简体   繁体   English

SQL使用listagg()并按非重复值分组

[英]SQL using listagg() and group by non duplicated values

        ID TELNO
---------- --------------------
         1 0123456789
         1 0207983498
         2 0124339848
         2 09348374834
         2 02387694364

How can i query the above table to get output like this: 我如何查询上表以获取如下输出:

        ID TEL_LIST
---------- --------------------
         1 0123456789,0207983498
         2 0124339848,09348374834,09348374834 

I know i can use the listagg() to concatenate the id's by grouping the columns. 我知道我可以使用listagg()通过对列进行分组来连接ID。 For example, 例如,

listagg(id',') within group (order by id) as idList 组(按ID排序)内的listagg(id',')作为idList

will return 1,2. 将返回1,2。

The TELNO column however cannot be grouped and the values are usually unique. 但是,TELNO列无法分组,并且值通常是唯一的。 How to do the concatenation on the second column where a group by is not possible? 在无法进行分组依据的第二列上如何进行串联?

Query: 查询:

SQLFIDDLEEXAMPLE SQLFIDDLEEXAMPLE

SELECT 
ID, LISTAGG(TELNO, ', ') 
WITHIN GROUP (ORDER BY TELNO) 
AS TEL_LIST
FROM   tbl
GROUP BY ID;

Result: 结果:

| ID |                             TEL_LIST |
---------------------------------------------
|  1 |               0123456789, 0207983498 |
|  2 | 0124339848, 02387694364, 09348374834 |

I Don't know whether you have put a unique constraint on ID,TELNO or not .If not ,we need to filter the unique values from the Table first and then apply LISTAGG as shown below: 我不知道您是否对ID,TELNO设置了唯一性约束。如果没有,我们需要首先从表中过滤唯一性值,然后应用LISTAGG ,如下所示:

  SELECT ID,
       LISTAGG(TELNO, ',') WITHIN GROUP (ORDER BY ID) AS TELNO
  FROM (
       SELECT UNIQUE
              ID,
              TELNO
         FROM tbl
       )
  GROUP BY ID;

SQLFIDDLE: LINK SQLFIDDLE: 链接

If you look to the execution place or the trace file ,the cost will be the same on the same set of data, with query JUSTIN suggested in the above solution 如果查看execution place or the trace file ,则在同一组数据上的成本将相同,在上述解决方案中建议使用查询JUSTIN

您可以使用wm_concat()函数执行相同的操作。

 select id,wm_concat(telno) from my_table group by id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM