This is an answer I gave to another poster, but it demonstrates exactly what you are asking for:
SELECT
seqid = identity(int, 1, 1),
event_id,
S.name
INTO #EventNames
FROM
celcat200809.dbo.CT_EVENT_STAFF ES
LEFT JOIN celcat200809.dbo.CT_STAFF S ON ES.staff_id = S.staff_id
ORDER BY
event_id,
S.name
SELECT
EN.event_id,
Max(CASE seqid - minseqid WHEN 0 THEN EN.name ELSE '' END))
+ Max(Coalesce(' + ' + CASE seqid - minseqid WHEN 1 THEN EN.name ELSE NULL END, ''))
+ Max(Coalesce(' + ' + CASE seqid - minseqid WHEN 2 THEN EN.name ELSE NULL END, ''))
+ Max(Coalesce(' + ' + CASE seqid - minseqid WHEN 3 THEN EN.name ELSE NULL END, ''))
+ Max(Coalesce(' + ' + CASE seqid - minseqid WHEN 4 THEN EN.name ELSE NULL END, ''))
+ Max(Coalesce(' + ' + CASE seqid - minseqid WHEN 5 THEN EN.name ELSE NULL END, ''))
+ Max(Coalesce(' + ' + CASE seqid - minseqid WHEN 6 THEN EN.name ELSE NULL END, ''))
+ Max(Coalesce(' + ' + CASE seqid - minseqid WHEN 7 THEN EN.name ELSE NULL END, ''))
+ Max(Coalesce(' + ' + CASE seqid - minseqid WHEN 8 THEN EN.name ELSE NULL END, ''))
+ Max(Coalesce(' + ' + CASE seqid - minseqid WHEN 9 THEN EN.name ELSE NULL END, ''))
+ Max(Coalesce(' + ' + CASE seqid - minseqid WHEN 10 THEN EN.name ELSE NULL END, ''))
FROM
#EventNames EN
INNER JOIN (
SELECT event_id, minseqid = Min(seqid) FROM #EventNames GROUP BY event_id
) X ON EN.event_id = X.event_id
GROUP BY EN.event_id
You can ignore the 10 Max() expressions. The key parts are:
- Stick the values into a temp table with an identity column, sorted in order by group.
- Get the min value per group with an aggregate query (derived table X above)
- Subtract the min value from the identity value (and add 1 if you need to start numbering at 1) and voila you have numbers that restart at 1 for each group!
If you're going to use the results of the select more than twice, then at creation time add another int column to the temp table and update it with the new numbers, instead of calculating it each time. I'm guessing about when performance will be better to do an update... testing is in order.