It sounds like you want something that is similar to mySQL's Group_Concat
in SQL Server?
If you are looking for a way to do this so that each companyid is in a separate column, then that would only be possible with some difficulty using dynamic SQL. At which time it might be easier to just return this to an application and let it handle what it needs within its own logic?
BTW, the dynamic SQL logic would go something like this in case you were wondering...notice how nasty it is...thus why I would suggest against it.
select @highestCount = max(count(*))
from employeeCompany
group by Employeeid
declare createtemptable varchar(max), @filltableselect varchar(max), @filltablejoin varchar(max)
declare @currentCount int
set @currentCount = 0
set @createtemptable = 'CREATE TABLE #Temp (EmployeeID INT'
set @filltableselect = 'INSERT INTO #Temp SELECT EmployeeCompany0.EmployeeID, EmployeeCompany0.CompanyID'
set @filltablejoin = 'FROM EmployeeCompany AS EmployeeCompany0'
while(@currentCount < @highestCount)
begin
set @createtemptable = @createtemptable + ', CompanyID'
+ CAST(@currentCount AS VARCHAR(2)) + ' INT'
if(@currentCount > 0)
begin
set @filltableselect = @filltableselect + ', EmployeeCompany'
+ CAST(@currentCount AS VARCHAR(2)) + '.CompanyId'
set @filltablejoin = @filltablejoin
+ 'LEFT JOIN EmployeeCompany AS EmployeeCompany'
+ CAST(@currentCount AS VARCHAR(2))
+ ' ON EmployeeCompany0.EmployeeID = EmployeeCompany'
+ CAST(@currentCount AS VARCHAR(2)) + '.EmployeeID'
end
set @currentCount = @currentCount + 1
end
set @createtemptable = @createtemptable + ')'
--This next line can be whatever you need it to be
set @filltablejoin = @filltablejoin + 'WHERE employeeCompany0.EmployeeID = 1'
exec @createtemptable
exec @filltableselect + @filltablejoin