The answer nes gave works great for MySql
and is correct answer to the question.
I was just curious about how to do that in Sql Server
since projecting a column that is not included in grouping is not allowed. So i came to accept this as a good solution;
DECLARE @table1 TABLE
(
id int primary key,
name nvarchar(50),
email nvarchar(50),
number int
)
INSERT INTO @table1 VALUES (1, 'name1', 'a@a.com', 1)
INSERT INTO @table1 VALUES (2, 'name1', 'b@b.com', 2)
INSERT INTO @table1 VALUES (3, 'name2', 'c@c.com', 5)
SELECT t1.name, t1.number, t1.email
FROM @table1 As t1 JOIN (SELECT name, MAX(id) As maxId FROM @table1 GROUP BY name) As t2
ON t2.maxId = t1.id
Alias t2
is the result of subquery which returns the distinct names with additional column id
information (MAX()
is used as aggregate to guarantee there will only be one name and no duplicates, it could be MIN()
aswell). t2
is joined with t1
on id
fields ensuring that there will be unique names.
The only constraint is; there must be an id
field or any other unique key
Just wanted to share, sorry if considered off-topic