Here you go:
DECLARE @t TABLE
(
id INT,
Name VARCHAR(20),
Role INT
)
INSERT INTO @t
SELECT ROW_NUMBER() OVER(ORDER BY Names.CustomerID, Roles.Role), Names.Name, Roles.Role
FROM @names AS Names
INNER JOIN @roles AS Roles ON Roles.CustomerId = Names.CustomerId
UPDATE @t
SET Name = NULL
FROM @t Temp1
WHERE EXISTS(SELECT TOP 1 1 FROM @t Temp2 WHERE Temp2.Name = Temp1.Name AND Temp2.id < Temp1.id)
SELECT * FROM @t
Replace @Names and @Roles with your table definitions.
You can also do this with temp tables or recursive CTE or cursors but a simple table variable will do fine.
For reference, my test code:
DECLARE @names TABLE
(
CustomerId INT,
Name VARCHAR(20)
)
DECLARE @roles TABLE
(
CustomerId INT,
Role INT
)
INSERT INTO @names VALUES (1, 'pete'), (2, 'dave'), (3, 'jon')
INSERT INTO @roles VALUES (1, 1), (1, 2), (2, 1), (3, 2), (3,3)
-- rest of query
My results differ from yours as I suspect you had a typo swapping with the first null and dave being swapped around:
Name, Role
pete 1
null 2
dave 1
jon 2
null 3
Edit: Having thought about it, you can actually do it without the temp tables at all:
SELECT CASE WHEN row_no = 1 THEN Name ELSE NULL END AS Name, Role
FROM
(
SELECT ROW_NUMBER() OVER(PARTITION BY Names.CustomerID ORDER BY Names.CustomerID, Roles.Role) As row_no, Names.Name, Roles.Role FROM @names AS Names
INNER JOIN @roles AS Roles ON Roles.CustomerId = Names.CustomerId
) x
Role=1haspete,nullbutRole=2hasdave,jon(and I see the answer you accepted returns something different from what you said you wanted anyway!)