tags:

views:

49

answers:

3

My table Tags has these records

Application   ID                                      TagName
/Blogs        A75FB4D9-B0A2-45B1-A58D-9CC4E7FC1482    TagA
/News         E1BDEF9D-4285-464F-88DC-00495B59D2AE    TagA
/News         997F1721-335B-477A-9943-B91F0C21DE74    TagB
/Blogs        BB1CEE87-AF8A-44D6-8A4B-EAB138BBEF10    TagB

I want to return only the first match of TagA and TagB, but the returning table must look exactly like the above (Application, ID, TagName), so I expect it to be:

/Blogs        A75FB4D9-B0A2-45B1-A58D-9CC4E7FC1482    TagA
/News         997F1721-335B-477A-9943-B91F0C21DE74    TagB

How can I do that?

+3  A: 

SQL Server 2005+

 SELECT Application, Id, TagName
 FROM
 (SELECT Application, Id, TagName,
  ROW_NUMBER()  OVER (partition by TagName order by TagName) rn
  FROM Table
 ) x 
 WHERE rn =1
Michael Pakhantsov
This will only work for SQL 2005 and up, which is probably what he has.
Philip Kelley
Incorrect syntax near the keyword 'WHERE'.
BrunoLM
You need to alias the inner select, replace `)` with `) r`
Jon Freedman
It returned one result with `/Blogs` and another with `/News`, all the other records where ignored. I want to get only distinct TagNames, so it is possible to return `/Blogs TagA`, `/Blogs TagB`, but not `/Blogs TagA`, `/Blogs TagA`.
BrunoLM
@BrunoLM, added removed TagName from partition clause
Michael Pakhantsov
Should be `ROW_NUMBER() OVER (PARTITION BY TagName ORDER BY Id)`
Jon Freedman
Fix it with Jon's comment and I will accept :)
BrunoLM
@BrunoLM, changed.
Michael Pakhantsov
Thank you Micheal and Jon.
BrunoLM
+1  A: 

This might do the trick...

SELECT MIN(Application), MIN(ID), TagName FROM Table GROUP BY TagName

In this example you will get an id that is not predictable...

Yves M.
Operand data type uniqueidentifier is invalid for min operator.
BrunoLM
CAST(MIN(CAST(ID as nvarchar(100))) as uniqueidentifier) i hate this approach but it works
Brian Rudolph
With Brian's fix it works. I wonder which is faster, this method or Michael's method?
BrunoLM
A: 

In the intesest of providing a non sql server specific answer

SELECT Application, Id, TagName
FROM Tags t
JOIN (
    SELECT Application, TagName, MAX(InsertOrder) LatestInsert
    FROM Tags
    GROUP BY Application, TagName
) l ON l.Application = t.Application AND l.TagName = t.TagName AND l.LatestInsert = t.InsertOrder

This assumes the existance of a column which allows you to identify a "first" match - note that if this is a timestamp its possible you may have two records with an identical insert time

Jon Freedman
Invalid column name 'InsertOrder'.
BrunoLM
I've added emphasis, and I repeat my earlier question, in your example resultset how do you decide that [Blogs,TagA] > [News,TagA]
Jon Freedman