|
-
Aug 21st, 2008, 02:45 PM
#1
Thread Starter
Hyperactive Member
Select Random Rows
Hi,
I have a table of products. Each product has a primary key (ID) and a foreign key (SubcategoryID). I want to randomly select 4 rows where SubcategoryID equals a given parameter.
How do I do this?
TIA,
Matt
VS 2010 / .NET 4.0 / ASP.NET 4.0
-
Aug 21st, 2008, 02:50 PM
#2
Re: Select Random Rows
If row repeatation is not an issue than you an use
Code:
SELECT TOP 4 * FROM Product WHERE SubcategoryID = Value
__________________
Rate the posts that helped you 
-
Aug 21st, 2008, 02:58 PM
#3
Re: Select Random Rows
Try this:
SQL Code:
SELECT TOP 4 * FROM Product WHERE SubcategoryID = Value
ORDER BY NEWID()
So what actually happens is that newid() returns a new GUID/unique identifier for every row in the result set, it then sorts based on the GUID value and then eventually selects the 4 top most rows.
Sometimes the Programmer
Sometimes the DBA
Mazz1
-
Aug 21st, 2008, 02:59 PM
#4
Thread Starter
Hyperactive Member
Re: Select Random Rows
But that just returns the same top 4 every time. is there a way to pick a random 4?
VS 2010 / .NET 4.0 / ASP.NET 4.0
-
Aug 21st, 2008, 03:00 PM
#5
Re: Select Random Rows
Must have crossed post #3
Sometimes the Programmer
Sometimes the DBA
Mazz1
-
Aug 21st, 2008, 03:02 PM
#6
Thread Starter
Hyperactive Member
Re: Select Random Rows
o I didn't see that. I thought it was part of your sig.
Sweet, I'll give it a try!
TY
VS 2010 / .NET 4.0 / ASP.NET 4.0
-
Aug 21st, 2008, 04:41 PM
#7
Thread Starter
Hyperactive Member
Re: Select Random Rows
gary,
I'm getting an error on Value. It says it's an invalid column.
VS 2010 / .NET 4.0 / ASP.NET 4.0
-
Aug 21st, 2008, 04:43 PM
#8
Thread Starter
Hyperactive Member
Re: Select Random Rows
i'm sorry. brain fart. I got it. Thanks!!
VS 2010 / .NET 4.0 / ASP.NET 4.0
-
Aug 22nd, 2008, 06:38 AM
#9
Re: Select Random Rows
If this resolves this issue could you please mark this thread as RESOLVED using the Thread Tools above. This will let anyone else looking for a similar issue that you have recieved a good answer to this question.
Sometimes the Programmer
Sometimes the DBA
Mazz1
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|