2

I need to retrieve the name or names of "CARGO#" separated by “,” filtered by "PNTO_VNTA"

I need the output in this way:

I need the output in this way

I have done many tests but they bring me the result in this way:

I have done many tests but they bring me the result in this way

This is the code that I am using

 SELECT
    s.PNTO_VNTA,
    LISTAGG (g.CARGO), ', ') WITHIN GROUP (ORDER BY g.CARGO) OVER()  PRODUCTOS
FROM
    PNTOS_VNTA s,
    CARGOS g
WHERE
    s.crgo = g.CARGO
    AND s.PNTO_VNTA = 12345
    GROUP BY s.PNTO_VNTA,
    g.cargo
    ;
Alex Poole
  • 183,384
  • 11
  • 179
  • 318

1 Answers1

0

You are grouping by both pnto_vnta and cargo, so you will get one row for each combination; the aggregate would then only have a single value. You seem to have tried to compensate for that by adding the over() clause to make the listagg() call analytic.

If you change both of those you should get what you want:

SELECT
    s.PNTO_VNTA,
    LISTAGG (g.CARGO, ', ') WITHIN GROUP (ORDER BY g.CARGO) PRODUCTOS
FROM
    PNTOS_VNTA s,
    CARGOS g
WHERE
    s.crgo = g.CARGO
    AND s.PNTO_VNTA = 12345
    GROUP BY s.PNTO_VNTA
    ;

Or with ANSI join syntax:

SELECT
    s.PNTO_VNTA,
    LISTAGG (g.CARGO, ', ') WITHIN GROUP (ORDER BY g.CARGO) PRODUCTOS
FROM PNTOS_VNTA s
JOIN CARGOS g ON s.crgo = g.CARGO
WHERE s.PNTO_VNTA = 12345
GROUP BY s.PNTO_VNTA
;

Although it doesn't look like you need the join; unless you have nulls or orphans you can probably just do:

SELECT
    s.PNTO_VNTA,
    LISTAGG (s.CRGO, ', ') WITHIN GROUP (ORDER BY s.CRGO) PRODUCTOS
FROM PNTOS_VNTA s
WHERE s.PNTO_VNTA = 12345
GROUP BY s.PNTO_VNTA
;

db<>fiddle

(I've left s.crgo in all of those; not sure if that's a typo in your question.)

Alex Poole
  • 183,384
  • 11
  • 179
  • 318
  • Thanks for answering, I've tried your solution getting rid of the `over()` but when I do that I get this error `ORA-01489: string concatenation result is too long` – Stiven Medina Aug 26 '21 at 17:24
  • You shouldn't for the example you showed, as it only has three cargo values. If you have other (real) `pnto_vnta` values that have a lot of `cargo` values then those would have exceeded the 4k string limit with the analytic version too. That's a different issue though, and has been asked many times before - [here](https://stackoverflow.com/q/13795220/266304) for example. – Alex Poole Aug 26 '21 at 17:28
  • I know for the first example I shouldn't get that error, but I still get it and don't know why, and I tried adding this `rownum = 1` but I get only one result in `cargo` – Stiven Medina Aug 26 '21 at 18:05
  • I'm not sure what you mean. I've added a db<>fiddle showing that it works. If you are doing something more complicated then as a new question with a [mcve] - including the DDL and sample data that demonstrates the problem. – Alex Poole Aug 26 '21 at 18:16