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
 Select statement with dynamic values

Author  Topic 

Legend1673
Starting Member

6 Posts

Posted - 2010-01-03 : 14:13:39
I am trying to complete a select statement where I want a specific number of records and these records have the smallest field value in relation the all the other records in the table.

EXAMPLE:
I need a query that will pull the 10,000 records with the oldest datetime value from the table?

I hope this makes sense.

set rowcount 10000
select * from TABLE where DATETIMEFIELD....???

Thanks,
Jeff

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-01-03 : 14:22:05
select top 10000 * from TABLE where DATETIMEFIELD = (SELECT MIN(DATETIMEFIELD ) FROM TABLE)
Go to Top of Page

Legend1673
Starting Member

6 Posts

Posted - 2010-01-03 : 15:45:39
That query would only return one value.

Assume this is the table and I need the oldest 3 records. (IDs 1,2,3)

ID DATETIME
1 2009-12-01 12:00:01.000
2 2009-12-01 12:00:02.000
3 2009-12-01 12:00:03.000
4 2009-12-01 12:00:04.000
5 2009-12-01 12:00:05.000

Thanks,
Jeff
Go to Top of Page

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2010-01-03 : 15:54:42
select top 3 * from your_Table order datetime_Column


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

Legend1673
Starting Member

6 Posts

Posted - 2010-01-03 : 16:48:32
Thank you.

I thought the order only sorted the sub-set. Didn't realize it ordered the table.

Thanks again,
Jeff
Go to Top of Page

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2010-01-03 : 17:06:50
welcome


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

- Advertisement -