简体   繁体   English

sql视图中的不同listagg

[英]distinct listagg in sql view

I have a table like this: 我有一张这样的桌子:

id  name
1   ben
1   ben
2   charlie
2   dan
2   edgar
3   frank

and i want the following columns to be part of an existing view in sql developer: 我希望以下各列成为sql developer中现有视图的一部分:

id  names
1   ben
2   charlie,dan,edgar
3   frank

I was able to generate the table (id, names) using listagg but i cant add it to the view (most popular error is invalid identifier). 我能够使用listagg生成表(ID,名称),但无法将其添加到视图中(最常见的错误是无效标识符)。

please let me know if more information is needed. 请让我知道是否需要更多信息。

thanks 谢谢

Use a sub-query to first select only the DISTINCT rows before applying LISTAGG . 在应用LISTAGG之前,使用子查询首先仅选择DISTINCT行。

For example, 例如,

Setup 设定

SQL> CREATE TABLE t
  2      (id int, name varchar2(7));

Table created.

SQL>
SQL> INSERT ALL
  2      INTO t (id, name)
  3           VALUES (1, 'ben')
  4      INTO t (id, name)
  5           VALUES (1, 'ben')
  6      INTO t (id, name)
  7           VALUES (2, 'charlie')
  8      INTO t (id, name)
  9           VALUES (2, 'dan')
 10      INTO t (id, name)
 11           VALUES (2, 'edgar')
 12      INTO t (id, name)
 13           VALUES (3, 'frank')
 14  SELECT * FROM dual;

6 rows created.

SQL>

Query 询问

SQL> WITH DATA AS(
  2  SELECT DISTINCT ID, NAME FROM t
  3  )
  4  SELECT ID,
  5    listagg(NAME, ',') WITHIN GROUP (
  6  ORDER BY ID) NAME
  7  FROM DATA
  8  GROUP BY ID;

        ID NAME
---------- -----------------------------
         1 ben
         2 charlie,dan,edgar
         3 frank

SQL>

Another way is to remove the duplicates from the aggregated values as answered here https://stackoverflow.com/a/27817597/3989608 . 另一种方法是从汇总值中删除重复项,如此处https://stackoverflow.com/a/27817597/3989608所示

For example, 例如,

SQL> SELECT id,
  2    RTRIM(REGEXP_REPLACE(listagg (name, ',') WITHIN GROUP (
  3  ORDER BY id), '([^,]+)(,\1)+', '\1'), ',') name
  4  FROM t
  5  GROUP BY id;

        ID NAME
---------- ---------------------------------------------
         1 ben
         2 charlie,dan,edgar
         3 frank

SQL>

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

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