Oracle中使用LISTAGG函数检索唯一值
Oracle的LISTAGG函数可以连接指定列中的值。但是,当从非唯一列检索值时,该函数可能会产生重复的结果。
问题:
使用LISTAGG函数,您希望仅从列中检索唯一值,而不必使用函数或过程。例如,考虑以下表格:
col1 | col2 |
---|---|
1 | 2 |
1 | 2 |
1 | 3 |
1 | 4 |
1 | 5 |
当您将LISTAGG应用于col2时,您可能会得到以下结果:[2,2,3,4,5]。目标是消除重复的2,只显示唯一值。
解决方案:
19c及更高版本:
<code class="language-sql">select listagg(distinct col2, ',') within group (order by col2) from the_table;</code>
18c及更早版本:
<code class="language-sql">select listagg(col2, ',') within group (order by col2) from ( select distinct col2 from the_table ) t;</code>
这些查询在LISTAGG函数中使用DISTINCT关键字,以确保只包含唯一值。
附加列:
如果您需要与唯一值一起检索多个列,您可以采用以下方法:
<code class="language-sql">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;</code>
此查询为col1和col2的每个组合分配一个唯一的行号,然后为每个col1组选择第一行。
以上是如何使用 Oracle 的 LISTAGG 函数仅检索不同的值?的详细内容。更多信息请关注PHP中文网其他相关文章!