Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Query + Group by + Concatenate

Author  Topic 

db_sysadmin
Starting Member

27 Posts

Posted - 2006-03-23 : 10:24:38
Hey there!,

I have this table:

Cli_ID....Criteria
..1..........1
..1..........2
..2..........1
..2..........2
..2..........3
..3..........1
..4..........1

And I want this query result,

Cli_ID....All_Criteria_Per_Client
..1..........1,2
..2..........1,2,3
..3..........1
..4..........1

I know I have to group by, but no idea how to concatenate each instance of criteria(TABLE).

Thanks a lot in advance!

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2006-03-23 : 11:39:05
You need to create a function that concatonates the criteria values by cli_id then use the function in a select:

set nocount on
use pubs
go
create table junk (Cli_ID int, Criteria int)
go

create function dbo.fn_criteriaByCliID(@cli_id int)
returns varchar(5000)
as
begin
declare @out varchar(5000)
select @out = coalesce(@out + ',' + convert(varchar,criteria), convert(varchar,criteria))
from junk
where cli_id = @cli_id

return @out
end

go
insert Junk
select 1,1 union all
select 1,2 union all
select 2,1 union all
select 2,2 union all
select 2,3 union all
select 3,1 union all
select 4,1
go

select cli_id, dbo.fn_criteriaByCliID(cli_id) criteria
from (
select cli_id
from junk
group by cli_id
) a

go
drop function dbo.fn_criteriaByCliID
drop table junk

---------------------------------------
output:
cli_id criteria
----------- -----------
1 1,2
2 1,2,3
3 1
4 1


Be One with the Optimizer
TG
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2006-03-24 : 05:36:42
And read this to know why you need function
http://sqljunkies.com/WebLog/amachanic/archive/2004/11/10/5065.aspx?Pending=true

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

db_sysadmin
Starting Member

27 Posts

Posted - 2006-03-24 : 15:44:34
Thanks so much guys! It' been so useful...
Go to Top of Page
   

- Advertisement -