Use order by newid () random number to select records in select distinct

Source: Internet
Author: User

In daily work, sometimes some activities may need to win the prize or select some spot check lists ,?
The order by newid () method is often used for random number selection ,?
However, it is possible that distinct should be used together. At this time, such as distinct and order by newid ()?
When used at the same time, an error message is displayed.

If select distinct is specified, the order by project must be displayed in the selection list 」.?
The following example shows the simplest solution .?
Here, the example database uses the example Chinese north wind database in Zhang Limin's book ,?
By using the Chinese example database, you can get closer to each other and learn about the results of this example .?

If you want to select the first 10 random numbers in this group of distinct data ,?
Then you may think of it directly?
Select distinct employee ID, delivery City?
From DBO. Ordering master?
Order by newid ()?
Of course, because distinct does not have newid () in the most filtered data, it will certainly happen?
If select distinct is specified, the order by project must be displayed in the selection list 」.?

It may be said that adding newid () to the SELECT statement makes order by no problem ,?
In this way, you may find the same effect as all select statements.

So what are the solutions to this problem ??
The distinct (filter) and order by newid () random numbers are sorted into two queries and combined,

Select Top 10? *?
From-simulate a data table?
(?
Select distinct employee ID, delivery City?
From DBO. Ordering master?
) As fictitious data table?
Order by newid ()

By filtering subqueries, newid () can be used to easily implement such functions.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.