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