To get the result, you will want to join the tables and apply the PIVOT function. I also suggest using the row_number() window function to get the number of warehouses for each client - this will be the value that will be used as the new column headings.
select customername, wh1, wh2, wh3 from ( select w.name warehousename, c.name customername, 'wh'+cast(row_number() over(partition by c.id order by w.id) as varchar(10)) seq from customer c inner join customerwarehouse cw on c.id = cw.customerid inner join warehouse w on cw.warehouseid = w.id ) d pivot ( max(warehousename) for seq in (wh1, wh2, wh3) ) piv;
See SQL Fiddle with Demo . If you have an unknown number of values, you will need to use dynamic SQL to get the result:
DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX) select @cols = STUFF((SELECT distinct ',' + QUOTENAME('wh'+cast(row_number() over(partition by customerid order by warehouseid) as varchar(10))) from customerwarehouse FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') set @query = 'SELECT customername, ' + @cols + ' from ( select w.name warehousename, c.name customername, ''wh''+cast(row_number() over(partition by c.id order by w.id) as varchar(10)) seq from customer c inner join customerwarehouse cw on c.id = cw.customerid inner join warehouse w on cw.warehouseid = w.id ) x pivot ( max(warehousename) for seq in (' + @cols + ') ) p ' execute sp_executesql @query;
See SQL Fiddle with Demo . Both give the result:
| CUSTOMERNAME | WH1 | WH2 | WH3 | | CustA | wh01 | (null) | (null) | | CustB | wh01 | wh02 | (null) | | CustC | wh01 | wh02 | wh03 |
Taryn source share