Q:

How to group by on selected column in sql?

How to apply a group by condition in a selected column
I want to apply group by condition only on name field of the "userdata" table.
SELECT CAST(UserId AS varchar(255)) AS UserId,
       CAST(name AS varchar(255)) AS name,
       CAST(city AS varchar(255))
FROM "userdata"
WHERE name = 'Jhohn'
GROUP BY CAST(UserId AS varchar(255)),
         CAST(name AS varchar(255)),
         CAST(city AS varchar(255));

The result of the above is
userId  name       city 
1       jhon       florida
2       sam        new york
3       sam        wales
4       thomas     new york

Expected results:
userId  name       city 
1       jhon       florida
2       sam        new york
4       thomas     new york

A:

You can also do this using following code
DECLARE @Table TABLE (UserId int, [Name] varchar(255), City varchar(255));
INSERT INTO @Table (UserId,[name], city)
VALUES(1,'Jhon', 'florida') 
,(2,'sam', 'New york')
,(3,'sam','wales')
,(4,'thomas','new york');

Select t.* from @Table t
inner join (
SELECT MIN(UserId) as UserId, Name
FROM   @Table
GROUP BY
       Name
)a on t.UserId = a.UserId

You can find the live demo Here

