March 27, 2007 at 12:02 pm
I'm trying to create a query that will collapse a 1->M into a single row with each of the values from the many side as fields
So if I have a table of facilities,
id description
1 Maryland
2 Delaware
3 Washington
I want to create a single row where the facility ids are columns
FacA FacB FacC
1 2 3
I've only gotten as far as getting a comma delimited list of the ids:
<code>
DECLARE @Facilities TABLE (facility_id INT, description VARCHAR(50))
INSERT INTO @Facilities (facility_id , description ) VALUES (1,'Facility 1')
INSERT INTO @Facilities (facility_id , description ) VALUES (2,'Facility 2')
INSERT INTO @Facilities (facility_id , description ) VALUES (3,'Facility 3')
DECLARE @FacilityList TABLE (facility_id int)
INSERT INTO @FacilityList (Facility_id)
SELECT Facility_ID FROM @Facilities
DECLARE @CommaDelimList varchar(max)
SET @CommaDelimList=''
SELECT @CommaDelimList=@CommaDelimList+CASE WHEN @CommaDelimList<>'' THEN ',' ELSE '' END + LTRIM(STR(facility_id))
FROM @FacilityList
SELECT @CommaDelimList
</code>
Any suggestions?
Rick Hodder
March 27, 2007 at 12:55 pm
this is what is known as a cross tab query; you are converting rows to columns. you can search for cross tab or pivot to find more examples:
here's an example with your data:
create table #test(id int,description varchar(30) )
insert into #test(id,description) values(1,'Maryland')
insert into #test(id,description) values(2,'Delaware')
insert into #test(id,description) values(3,'Washington')
insert into #test(id,description) values(1,'somethingelse')
insert into #test(id,description) values(2,'more')
insert into #test(id,description) values(3,'data')
SELECT
CASE WHEN id=1 then description else NULL END AS FACA,
CASE WHEN id=2 then description else NULL END AS FACB,
CASE WHEN id=3 then description else NULL END AS FACC
FROM #TEST
sample results:
FACA | FACB | FACC |
Maryland | NULL | NULL |
NULL | Delaware | NULL |
NULL | NULL | Washington |
somethingelse | NULL | NULL |
NULL | more | NULL |
NULL | NULL | data |
Lowell
Viewing 2 posts - 1 through 1 (of 1 total)
You must be logged in to reply to this topic. Login to reply