Link to home
Start Free TrialLog in
Avatar of Mike Littlewood
Mike LittlewoodFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Follow on question

This is a follow on question from

https://www.experts-exchange.com/questions/21759179/Create-one-row-of-data-from-a-column-of-data.html

Is there a way to make this work so that it only returns one instance of the JOB, for example ID 0 has JOB J3 twice and ID 1 has JOB J2 twice

ID     JOB
0     J1
0     J2
0     J3
0     J3
1     J2
1     J2
1     J3
2     J4
2     J5
3     J3

and I would like to return a dataset in this format.

ID     JOB
0     J1, J2, J3
1     J2, J3
2     J4, J5
3     J3
Avatar of Mike Littlewood
Mike Littlewood
Flag of United Kingdom of Great Britain and Northern Ireland image

ASKER

Original code was

create function dbo.CollectJobs ( @id int )
returns varchar(8000)
as
begin
  declare @res varchar(8000)
  select @res = coalesce ( @res + ',' , '' ) + JOB
  from yourtable where ID =  @ID

  return (@res )
end


and use this function:

select id, dbo.CollectJobs ( id) as Jobs
from yourtable
group by id
ASKER CERTIFIED SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Just add a GROUP BY clause to your function, as in:

CREATE function dbo.CollectJobs (@id int)

returns varchar(8000)

as

BEGIN

declare @res varchar(8000)

select      @res = coalesce ( @res + ',' , '' ) + JOB
From      yourtable
where      ID =  @ID
Group By JOB

return @res

END
Oops, I should have refreshed.
Great that has worked fine thanks.