In daily operations, sometimes it may be that some activities to draw out the winners or select some of the list, It is often used to order by Newid () the way to do random number selection, but the possible situation needs to be matched to DISTINCT to choose, this time, such as DISTINCT and Order by Newid () will encounter error message /c7>
"If you have specifiedSELECT DISTINCT, youORDER byThe item must appear in the Pick list.The following example shares one of the simplest approaches. Here the sample database is used Zhang Limin Example of a teacher in the book Chinese North Wind Database,By using the sample database in Chinese, we can get a closer look at the effect of this example.If you want to be in this groupDISTINCTRandom number selection at the beginning of data10PenYou might be able to associate it directly with theSELECT DISTINCTEmployee number,Delivery CityFROM dbo.Order main FileOrder by NEWID ()Of course becauseDISTINCTWithin the most filtered data, there is no newid () It's going to happen. "if you have specified select Distinct ORDER by The item must appear in the Pick list. newid () add it in. select inside, so order by There's no problem. So if you use the words, the effect may be that you will find it with all select
so much for that. , what is the solution to the ? DISTINCT ( screening) Order by Newid () random numbers sorted into two queries, grouped together,
Select TOP * from- Simulation of a data sheet (SELECT DISTINCT employee number , shipping city from dbo. Order main file ) as fictitious data table order by newid ()
By filtering the subquery first, the use of newid () will be able to make such a function easily
SQL Server:
Select TOP N * from TABLE Order by NewID () view plaincopy to Clipboardprint? Select TOP N * from TABLE Order by NewID ()
Select TOP N * from TABLE the Order by NewID () NewID () function creates a unique value of type uniqueidentifier. The above statement achieves the effect of randomly reading N records from a table.
Access:
Select TOP N * from TABLE Order by Rnd (ID) view plaincopy to Clipboardprint? Select TOP N * from TABLE Order by Rnd (ID)
Select TOP N * from TABLE Order by Rnd (ID) Rnd (ID) where the ID is an AutoNumber field that can be done with any other value, such as using the Name field (UserName)
Select TOP N * from TABLE Order by Rnd (Len (UserName)) view Plaincopy to Clipboardprint? Select TOP N * from TABLE Order by Rnd (Len (UserName))
Select TOP N * from TABLE Order by Rnd (Len (UserName))
Mysql:
Select * from TABLE Order by Rand () Limit ten view plaincopy to Clipboardprint? Select * from TABLE Order by Rand () Limit 10
Select * from TABLE Order by Rand () Limit 10
PostgreSQL:
SELECT * from glxt022 order by random () Limit 5 view plaincopy to Clipboardprint? SELECT * from glxt022 order by random () limit 5
Order by NEWID () random query