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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Find Last

Author  Topic 

baze7
Yak Posting Veteran

58 Posts

Posted - 2010-10-27 : 09:12:28
I am coming from a different programming language. I am used to a find last and find first statement. How is that done is SQL?

Thanks

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2010-10-27 : 09:31:46
Can you give an example for what would be last or first in your mind?


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

baze7
Yak Posting Veteran

58 Posts

Posted - 2010-10-27 : 09:43:45
Sure. Table named 'Cars' and field 'Make' and a field 'Serial#' make is ford all the time and Serial # is different. How can I dinf the first serial #? Then a differnet query to find the last? Make sense?
Go to Top of Page

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2010-10-27 : 10:03:46
If Serial# is in ascending order from first to last.
There are many ways and here is one example:

-- get the 'first'
SELECT * FROM Cars
WHERE make = 'Ford'
and [Serial#] = (SELECT MIN([Serial#]) from Cars where make = 'Ford')

-- for 'last' just do the same with MAX() instead of MIN().


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

Kristen
Test

22859 Posts

Posted - 2010-10-27 : 10:57:40
SELECT TOP 1 Col1, Col2, ...
FROM Cars
WHERE make = 'Ford'
ORDER BY [Serial#] DESC
Go to Top of Page

Kristen
Test

22859 Posts

Posted - 2010-10-27 : 10:58:41
"How can I dinf the first serial #?"

Sorry, missed that bit, use ASC (Ascending) in the ORDER BY to find the first one
Go to Top of Page

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2010-10-27 : 11:05:41
As I said there are many ways and I am sure this thread will be continued...the next mate will come up with ROW_NUMBER() or so


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

Kristen
Test

22859 Posts

Posted - 2010-10-27 : 12:43:10
I wouldn't use ROW_NUMBER() unless there was a need for the First, or Last, row for EACH model ...
Go to Top of Page
   

- Advertisement -