OracleでLISTAGGを使用して個別の値を返す 質問する

OracleでLISTAGGを使用して個別の値を返す 質問する

Oracle で関数を使用しようとしていますLISTAGG。その列の一意の値のみを取得したいと思います。関数やプロシージャを作成せずに一意の値のみを取得する方法はありますか?

  col1 col2 作成者
   1 2 スミス
   1 2 ジョン
   1 3 アジェイ
   1 4 ラム
   1 5 ジャック

col1 と col2 を選択する必要がありますLISTAGG(列 3 は考慮されません)。これを実行すると、次のような結果になりますLISTAGG[2,2,3,4,5]

ここでは重複した「2」を削除する必要があります。col2 と col1 の異なる値のみが必要です。

ベストアンサー1

19c 以降:

select listagg(distinct the_column, ',') within group (order by the_column)
from the_table

18c 以前:

select listagg(the_column, ',') within group (order by the_column)
from (
   select distinct the_column 
   from the_table
) t

より多くの列が必要な場合は、次のようなものが必要になる可能性があります。

select col1, listagg(col2, ',') within group (order by col2)
from (
  select col1, 
         col2,
         row_number() over (partition by col1, col2 order by col1) as rn
  from foo
  order by col1,col2
)
where rn = 1
group by col1;

おすすめ記事