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.
| Author |
Topic |
|
swims01
Yak Posting Veteran
59 Posts |
Posted - 2009-06-24 : 14:12:36
|
Sorry for the confusing subject.We have a table that tracks a company: tblCompany. A seperate table tracks facility: tblFacility. From these we can see which company has access to which Facility.tblCompany (C) has an IDtblFacility (F) has the Company ID and Facility ID'sex. Companies 1, 2 / Facilities A, B, CCompany 1 has access to Facility A & CCompany 2 has access to Facility B & CtblFacilityCompany ID / Facility ID1 , A1 , C2 , B2 , CIf we run a normal Select statement we would get 4 rows of results.How can we get the following result...Company 1 has access to Facility A, CCompany 2 has access to Facility B, Cselect 'Company ' + c.id + ' has access to Facility ' + (????) as [Description]from tblCompany Cinner join tblFacility F on c.ID = F.ID Does that make sense? Sorry for any confusion.Thanks. |
|
|
vijayisonly
Master Smack Fu Yak Hacker
1836 Posts |
Posted - 2009-06-24 : 14:21:24
|
| If you already know the number of facilities..you can try this..declare @t table (cid int)insert @tselect 1 union allselect 2declare @r table (cid int, fid char(1))insert @rselect 1,'A' union allselect 1,'B' union allselect 2,'B' union allselect 2,'C' select 'Company ' + convert(varchar(1),r.cid) + ' has access to facilities ' + max(case when rownum = 1 then r.fid else null end) + ' , ' +max(case when rownum = 2 then r.fid else null end)from @t tinner join (select row_number () over(partition by cid order by fid) as rownum,* from @r) ron t.cid = r.cidgroup by r.cid |
 |
|
|
swims01
Yak Posting Veteran
59 Posts |
Posted - 2009-06-24 : 14:41:51
|
| We have ~100 companies so it has to be dynamic |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-06-25 : 14:04:40
|
if you're using sql 2005 use thisselect distinct 'Company ' + convert(varchar(10),t.cid) + ' has access to facilities ' + stuff((select ','+ fid from @t where cid=t.cid for xml path('')),1,1,'')from @t t |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-06-25 : 14:12:18
|
if sql 2000 useCREATE FUNCTION GetFacilities(@Cid int)RETURNS varchar(8000) ASBEGINDECLARE @FacilityList varchar(8000)SELECT @FacilityList=COALESCE(@FacilityList+ ',','') + fidFROM YourTableWHERE Cid=@CidRETURN @FacilityListENDthen use it like belowSELECT distinct 'Company ' + convert(varchar(10),cid) + ' has access to facilities ' + dbo.GetFacilities(cid)from yourtable |
 |
|
|
|
|
|
|
|