NewID () with additional conditions

Source: Internet
Author: User

I met a business requirement the day before yesterday, which made it hard for team members,

The table structure is as follows:

Create table [dbo]. [Product] (
[P_ID] [bigint] IDENTITY (1, 1) not null,
[P_Name] [nvarchar] (255) NULL,
[CategoryID1] [int] NULL,
[CategoryID2] [int] NULL,

[CategoryID3] [int] NULL,

[P_SingleIntro] [nvarchar] (200) NULL,


[LoginID] [nvarchar] (50) NULL,

CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED
(
[P_ID] ASC
)

You need to randomly list a product of each user (loginid) in the table, and the random values are not repeated each time.

So consider using newid ()

Select max (P_ID) as P_ID, loginID from product
Group by loginid order by NewID ()

The P_ID obtained each time is the same! Not meeting requirements

Modify the settings as follows:

Select P_ID, LoginID, P_Name, P_SingleIntro from product where P_ID in
(
Select (select top 1 p_id from product as B where B. loginid = c. loginid order by newid () as p_id
From (select top 10000 a. loginID from product as a group by a. loginid order by NewID () as c
)
-- Assume that the first 10000 users are used.

OK !!!! (It's just a bit cool! ^_^)

Thanks to dust.
This can be done in SQL 2005/2008.

Code

Select P_ID, LoginID, P_Name, P_SingleIntro
From (select P_ID, LoginID, P_Name, P_SingleIntro,
ROW_NUMBER () over (partition by loginID order by new) rn from (select *, NEWID () new from Product) as temp)
Te where rn = 1 and LoginID is not null and Len (loginID)> 0
Order by loginid asc

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.