Given the following table, lacking any unique key, how can I group by id and get the Permissions column with the longest length?
SampleTable:
id | Permissions
------------------------------------
1 | Walk, Swim
1 | Walk, Sit, Swim, Run, Jump, Lay
1 | !Walk, Sit, Lay
2 | Walk, Sit, Swim
3 | !Walk, Sit, Swim
3 | Walk, Sit, Swim
I tried:
SELECT r.id, r.Permissions
FROM SampleTable AS r
CROSS APPLY (
SELECT TOP 1 u.id, u.Permissions
FROM SampleTable AS u
GROUP BY u.id, u.Permissions
HAVING u.id = r.id
ORDER BY MAX(LEN(Permissions)) DESC
) AS u
However I didn't get the correct results.
I'm looking for results like:
id | Permissions
-----------------------------------
1 | Walk, Sit, Swim, Run, Jump, Lay
2 | Walk, Sit, Swim
3 | !Walk, Sit, Swim
Edit:
This has already been answered, thanks. But as an aside, I should have had my SQL as:
SELECT r.id, u.Permissions
FROM SampleTable AS r
CROSS APPLY (
SELECT TOP 1 u.id, u.Permissions
FROM SampleTable AS u
WHERE u.id = r.id
ORDER BY LEN(Permissions) DESC
) AS u
GROUP BY r.id, u.Permissions