1
votes

I am trying to display group by field name after doing sum of columns in Oracle SQL Developer, but not getting.

Following is my data -

enter image description here

Looking for output as follow -

enter image description here

Here is my query -

Select ID,Name, Sum(Amount) From Table1 Group By Name Order By SUM (Amount)DESC;

1

1 Answers

1
votes

You can use listagg() but eliminating duplicates is tricky, because it doesn't support distinct. One method uses row_number() and case:

select id,
       listagg(case when seqnum = 1 then name end, ',') within group (order by name desc) as names,
       sum(amount)
from (select t.*, row_number() over (partition by id, name order by id) as seqnum
      from table1 t
     ) t
group by id;

listagg() ignores NULL values.

Here is a db<>fiddle.