tags:

views:

174

answers:

2

I have a table like this:

ID  CatID  Filename
 1    1      abc
 2    2      abc
 3    3      cat
 4    2      dog
 5    1      dog

What I want to do is get just 1 ID per filename. I dont mind what ID i get i.e. the first or the last. How would I go about doing this?

+4  A: 
SELECT MIN(ID), FileName
FROM YourTable
GROUP BY FileName

Will get you the first ID for each filename

AdaTheDev
Technically, it won't necessarily be the first ;-)
Yannick M.
Are you sure this will get the "first" ID from an I/O perspecitve?
John Sansom
Depends on definition of First - assuming ID is an identity column, it will be the first :)There is no FIRST() function in SQL Server
AdaTheDev
First in sense of first-one-created-assuming-identity-column-auto-assigned-by-sql-server :)
AdaTheDev
"assuming ID is an identity column, it will be the first" - Only if your Clustered Index is on your ID, which is often the case, but there are (some) times when it shouldn't be.
Russell Steen
@Russell - that's why I then clarified further in my next comment! Definition of the the term "first" is not relevant to this question - getting waaaay too much coverage :D
AdaTheDev
putting-dashes-between-every-word-in-a-sentence-makes-it-really-hard-to-readSorry for replying when you'd already addressed it, i overlooked your sentence as code, not english :)
Russell Steen
+2  A: 
-- Will get you the min
SELECT MIN(ID), FileName
FROM table
GROUP BY FileName

-- Will get you the max
SELECT MAX(ID), FileName
FROM table
GROUP BY FileName
Yannick M.
on my SQL Server 2005 box: _select first(id)_ results in Msg 195, Level 15, State 10, Line 1'first' is not a recognized built-in function name.
KM
First() is not a sql function!!!
AutomatedTester
Which DBMS do support 'FIRST()' and 'LAST()' and are these anything other than synonyms for 'MIN()' and 'MAX()' - and if not synonyms, what is the difference between 'FIRST()' and 'MIN()', or between 'LAST()' and 'MAX()'?
Jonathan Leffler
In SQL 2003, FIRST is not an aggregate function; it is a keyword, but it appears in DEPTH FIRST SEARCH and BREADTH FIRST SEARCH and FETCH FIRST and NULLS FIRST. LAST only appears in the last two contexts.
Jonathan Leffler
FWIW: I went searching on MySQL as a likely place - I found a reference to someone migrating from MS Access confused about the absence of FIRST in MySQL.
Jonathan Leffler
Oracle, MS Access, MySQL implements First() by default for every column in the select that is not Grouped on
Yannick M.