【问题标题】:SQL query with listagg (distinct ) and case statement带有 listagg (distinct) 和 case 语句的 SQL 查询
【发布时间】:2020-03-28 23:51:16
【问题描述】:

我需要使用listagg(distinct somestring),除非我需要有条件地选择记录,因此我在listagg 中组合了一个case 语句。

这是一个有效的代码示例:

listagg(case when  level_1='Brakes' and service_r_L>0.8 then  level_2 else null end  ,'+') within group (order by level_2 asc ) as Brake_services

但是我需要listagg(DISTINCT level_2 , '+'),但我无法将 DISTINCT 放在任何地方。

对不起SQL代码是小写的,可能只有我懒得把我的SQL代码大写。

【问题讨论】:

  • 您使用的是哪个 dbms?
  • 发布您的完整查询
  • 小写SQL就可以了,完全不需要大写。 (回到 80 年代大写是标准方式,但那是很久以前的事了。)

标签: sql oracle string-aggregation listagg


【解决方案1】:

Oracle 19c 允许这样做:LISTAGG DISTINCT in Oracle Database 19c 在本文中,您可以找到两个 19c 之前的解决方案:首先准备不同的值或使用 row_number()。还有第三种方法,正则表达式来删除输出中的重复项。这是第一种方式的例子,可能会对您有所帮助。如果没有,请编辑您的问题,告诉我们您使用的是哪个 Oracle 版本,向我们展示您的完整查询和示例数据,最好像我一样使用dbfiddle

dbfiddle demo

select id_grp, listagg(case when level_1 = 'Brakes' and srl = 1
                            then level_2 end  ,'+') 
                       within group (order by level_2 asc ) as brake_services
  from (select distinct id_grp, level_1, level_2, 
               case when service_r_l > .8 then 1 else 0 end srl from t)
  group by id_grp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-21
    • 1970-01-01
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多