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
 General SQL Server Forums
 New to SQL Server Programming
 SELECT query (rows returned in one column)?

Author  Topic 

gbaia
Yak Posting Veteran

52 Posts

Posted - 2005-08-17 : 12:26:31
Hi there,

I¡¦ve got a table with the following as well as other info:

User ID
DirectoryTypeID (int)
Region ID (int)

I need to run a query where I could get the region ID, then, in the second column, I¡¦d get all distinct directory types within that region. For example, if I run the query:

subRegionAreaID directoryTypeID
--------------- ---------------
3 1
3 2
3 3
3 9

If need these results to be:

subRegionAreaID directoryTypeID
--------------- ---------------
3 1, 2, 3, 9

Is this possible?

Many Thanks!! ļ


Grazi

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2005-08-17 : 13:16:01
One way is to create a function that builds the comma seperated string and call it once for each region:

set nocount on
--==========================================
--DDL/DML

--table
create table myTable
(regionid int
,typeid int)
go

--table data
insert myTable
select 1,1 union all
select 1,2 union all
select 1,3 union all
select 2,1 union all
select 2,2
go

--function to build comma seperated string of typeids
create function dbo.fnBuildCSVTypeIDs (@regionid int)
returns varchar(50)
as
begin
declare @str varchar(50)
select @str = coalesce(@str + ', ' + convert(varchar,typeid), convert(varchar,typeid))
from myTable
where regionid = @regionid
order by typeid

return @str
end
go

--==========================================
--select statement using the function
select regionid
,typeIDs = dbo.fnBuildCSVTypeIDs(regionid)
from myTable
group by regionid

--==========================================
--cleanup
go
drop function dbo.fnBuildCSVTypeIDs
drop table myTable
go


Be One with the Optimizer
TG
Go to Top of Page
   

- Advertisement -