Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 SQL Statement

Author  Topic 

Stéphane
Starting Member

1 Post

Posted - 2012-08-20 : 04:02:37
I have the folowing table trjtodo with folowing columns
ID
Color
Name

there are several rows where the same NAME occurs. I want the ID and color from the all the rows with first occurance of a NAME

ex.
1 | Blue | John
2 | Red | Sam
3 | Yellow | John
4 | Red | Sonia

what I need is an SQL statement that returns

1 | blue | John
2 | Red | Sam
4 | Red | Sonia

I tried : Select id, color, min(name) name from trjtodo group by 1,2
but it returns me the 4 rows.

thanks for helping me out here !

Regards,



Abu-Dina
Posting Yak Master

206 Posts

Posted - 2012-08-20 : 04:24:51
[code]create table dbo.test (ID int not null identity(1, 1),
colour varchar(20),
Name varchar(20))


insert into dbo.test (colour, name)
select 'Blue', 'John' union all
select 'Red', 'Sam' union all
select 'Yellow', 'John' union all
select 'Red', 'Sonia'


select a.ID, a.Colour, a.Name from (
SELECT ID, Colour, Name,
RANK() OVER (PARTITION BY Name order by ID) as ranking
FROM dbo.test) as a
where a.ranking < 2


drop table dbo.test
[/code]
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2012-08-20 : 05:21:37
You can't reference columns with ordinal positions when doing GROUP BY.
Spell out the column names and you should be fine.


group by 1,2

group by colour, name



N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page
   

- Advertisement -