Skip to content
Advertisement

How to use listagg properly with case statements

I am trying to use listagg but I’m getting the wrong output. Normally, I would use each case statement separately, but then how would I use listagg?

Table A:

Table B:

Desired Output:

My attempted (wrong) code:

Advertisement

Answer

Here’s one option, which uses multiple self-joins.

  • lines #1 – 14 represent your sample data
  • anima CTE is here to simplify code; better have it in a table (even if it is a CTE) than use CASE
  • the final result, lines #24 – 34, concatenates animal names
    • trim + regexp_replace is used to remove superfluous commas

Here you go:

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement