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
 Filtering data by getting only distinct columns

Author  Topic 

Apples
Posting Yak Master

146 Posts

Posted - 2013-01-11 : 15:48:15
I have a query

SELECT *
FROM tblMyTable

that returns these results:

ID | TypeID | Name
----------------------------------
1 | 1 | AAA
2 | 1 | BBB
3 | 2 | CCC
4 | 4 | DDD
5 | 5 | EEE
6 | 5 | FFF
7 | 5 | GGG

I'd like to filter the results so that there are only distinct TypeIds, so that the results returned are:

ID | TypeID | Name
----------------------------------
1 | 1 | AAA
3 | 2 | CCC
4 | 4 | DDD
5 | 5 | EEE

How can I change my query to do that?

adry_fab
Starting Member

1 Post

Posted - 2013-01-11 : 16:38:36
SELECT
MIN(ID),
TypeID,
min(Name)
FROM tblMyTable
GROUP BY TypeID
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-01-12 : 03:27:31
[code]
SELECT ID,TypeID,Name
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY TypeID ORDER BY ID) AS Seq,*
FROM table
)t
WHERE Seq=1
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -