Ok, I've searched but can't find anything as specific as I'm trying to do here. I have two different tables that I need info from. This is a sample schema - similar to what I'm working from:
create table Nodes(
Caption varchar(max),
IP_Address varchar(max),
NodeID varchar(max)
);
insert into Nodes (Caption, IP_Address, NodeID)
values ('dev-srvr', '10.0.0.1', '29023');
insert into Nodes (Caption, IP_Address, NodeID)
values ('prod-srvr', '10.0.2.1', '29056');
insert into Nodes (Caption, IP_Address, NodeID)
values ('test-srvr', '10.1.1.1', '29087');
create table Volumes(
Caption varchar(max),
NodeID varchar(max)
);
insert into Volumes (NodeID, Caption)
values ('29023', '/');
insert into Volumes (NodeID, Caption)
values ('29023', '/boot');
insert into Volumes (NodeID, Caption)
values ('29023', '/dev/shm');
insert into Volumes (NodeID, Caption)
values ('29023', '/home');
insert into Volumes (NodeID, Caption)
values ('29056', '/');
insert into Volumes (NodeID, Caption)
values ('29056', '/var');
insert into Volumes (NodeID, Caption)
values ('29056', '/opt');
insert into Volumes (NodeID, Caption)
values ('29087', '/tmp');
I'm attempting to write a query (with a where clause...will have multiple a filters on final version) that will return Node.Caption, IP_Address, and every Volumes.Caption associated (based on NodeID). The number of entries in Volumes.Caption for each NodeID is dynamic and varies from 1 to about 60 or so. All I know how to write is this:
select Nodes.Caption, Nodes.IP_Address, Volumes.Caption as Volume
from Nodes with (nolock)
inner join Volumes
on Nodes.NodeID=Volumes.NodeID
where IP_Address like '10.0%'
Which returns the following:
Caption | IP_Address | Volume
---------------------------------
dev-srvr | 10.0.0.1 | /
dev-srvr | 10.0.0.1 | /boot
dev-srvr | 10.0.0.1 | /dev/shm
dev-srvr | 10.0.0.1 | /home
prod-srvr | 10.0.0.1 | /var
prod-srvr | 10.0.0.1 | /opt
But what I need is a single ROW per NodeID showing Node.Caption, IP_Address and all matching Volumes if possible. Like this (the final column names are not important...can be anything):
Caption | IP_Address | Volume1 | Volume2 | Volume3 | Volume 4
----------------------------------------------------------------
dev-srvr | 10.0.0.1 | / | /boot | /dev/shm | /home
prod-srvr | 10.0.0.1 | /var | /opt
There's 100 pivot examples on SO so I wanted to show a way that you could do this, which isn't as good as pivot, but works for your instance. It may not fit your entire dataset and was based on your sample data only.
Of note, your test data doesn't provide the results you claim they do. Probably just a typo on the insert.
USING DYNAMIC PIVOT