Let's asume I have a parent-child structure setup in SQL (server 2005):
CREATE TABLE parent (Id INT IDENTITY PRIMARY KEY, Name VARCHAR(255))
CREATE TABLE child (Id INT IDENTITY PRIMARY KEY, parentId INT, Name VARCHAR(255))
insert into parent select 'parent with 1 child'
insert into parent select 'parent with 2 children'
insert into child(name, parentid) select 'single child of parent 1', 1
insert into child(name, parentid) select 'child 1 of 2 of parent 2', 2
insert into child(name, parentid) select 'child 2 of 2 of parent 2', 2
Is there a way to return one row per parent with it's children as columns? Like:
parent.Id, parent.Name, child(1).Id, child(1).Name, child(2).Id, child(2).Name
Started out with:
select * from parent p
left outer join child c1 on c1.parentid = p.id
look at the pivot functionality if you use sql server 2005
If you want a different look try this
Sample data
Query
Output
Try with dynamic pivoting
Test data
Query
Output:
After looking at Damir Sudarevic's answer I came up with this: (see my question for table structure)
Your example is close to pivoting, but I do not think that pivot functionality is usable on this one.
I have renamed your example to use "department-person", instead of "child-parent", just to keep my sanity.
So, first tables and some data
Now I want to flatten the model, I'll use temporary table because I have table variables -- but a view on "real tables" would be good too.
Dynamic columns means dynamic query, I will compose it row-by-row into a table
And now, concatenate all query rows into a variable and execute
And here is the result:
alt text http://www.damirsystems.com/dp_images/morepivot_result_01.png