0

I have a data set as such

id     firstevent   allevents
1       apple       apple, orange
1       apple       apple
1       orange      orange,apple
2       orange      orange,apple
2       orange      orange,apple
3       apple       apple
4       banana      banana,orange, apple
4       orange      orange, apple
4       apple       apple

I am using a STRING_AGG to concatenate all values for each Id with the below Query.

SELECT  id,
STRING_AGG(FirstEvent,';') as FirstEvent ,
STRING_AGG(FirstEvent,';') as allEvents
from mProcessingTime 
  GROUP BY id

My output is like below:

id      FirstEvent                allevents
1       apple; apple; orange      apple, orange; apple; orange,apple
2       orange;orange             orange,apple; orange,apple
3       apple                     apple
4       banana; apple; orange     banana,orange, apple; orange, apple; apple

I want to modify this output to only the distinct values in the set. My expected output is:

id      FirstEvent                 allevents
1       apple; orange             apple, orange; apple; orange,apple
2       orange                    orange,apple
3       apple                     apple
4       banana; apple; orange     banana,orange, apple; orange, apple; apple

I tried using distinct inside the STRING_AGG function, but it isnt working.

Can you help me?

EDIT: added additional information for a clearer picture.

eshirvana
  • 20,424
  • 3
  • 21
  • 36
AlisonGrey
  • 473
  • 1
  • 6
  • 20

2 Answers2

1

I used one column to illustrate the solution but you got the idea:

select id,
STRING_AGG(FirstEvent,';') as FirstEvent 
, STRING_AGG(case when rw = 1 then FirstEvent else null end,';') as allevents 
from (
select * , row_number() over (partition by id,firstevent order by id) rw
from xx
) t
group by t.id
eshirvana
  • 20,424
  • 3
  • 21
  • 36
0

One option is to use distinct and subquery as follows:

SELECT top 10 id,
STRING_AGG(FirstEvent,';') as FirstEvent 
from (select distinct id  firstevent from mProcessingTime ) t
  GROUP BY id
Popeye
  • 34,995
  • 4
  • 9
  • 31