The problem that you are having is with the following line:
row_number() over (partition by [Id] order by id) as row,
This is creating a unique number for each row in your contacts
table but you are partitioning the table by the id
column which appears to be a unique value already for each row.
You should be partitioning the data based on the number of rows that exist in the contact_company_relation
table instead.
I also would alter the code to something like the following:
select company_name,
Contact1, Contact2, Contact3,
Contact4, Contact5
from
(
select c.first_name + ' ' + c.last_name as contact_name,
comp.company_name,
'Contact'+
cast(row_number() over(partition by ccr.company_id
order by ccr.contact_id) as varchar(1)) row
from contacts c
inner join contact_company_relation ccr
on c.id = ccr.contact_id
inner join contacts comp
on ccr.company_id = comp.id
) d
pivot
(
max(contact_name)
for row in (Contact1, Contact2, Contact3,
Contact4, Contact5)
) p;
See SQL Fiddle with Demo. This gives a result:
| COMPANY_NAME | CONTACT1 | CONTACT2 | CONTACT3 | CONTACT4 | CONTACT5 |
|--------------|------------|------------|------------|----------|----------|
| Analist | Ori Reshef | Ben Gurion | Ofer Jerus | (null) | (null) |
| Bar Net | Maya Leshe | Yossi Farc | Dima Brods | (null) | (null) |