帶附加條件的NewID 用法 downmoon

2021-08-29 15:19:18 字數 1695 閱讀 3903

前天碰到一業務需求,難倒了團隊成員,

表結構如下:

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

keyclustered

([p_id

]asc)

需要隨機列出表中每位使用者(loginid)的乙個產品,每次列出時隨機值不重複。

於是考慮用newid()

select

max(p_id)

asp_id,loginid

from

product

group

byloginid

order

bynewid()

結果每次取到的p_id都是相同的! 不符合需求

再修改如下:

select

p_id,loginid,p_name,p_singleintro

from

product

where

p_id

in(select

(select

top1

p_id

from

productasb

where

b.loginid

=c.loginid

order

bynewid

())as

p_id

from

(select

top10000

a.loginid

from

productasa

group

bya.loginid

order

bynewid

())as

c)--假定取前10000個使用者

ok!!!!(就是效能寒磣了點!^_^ )

感謝塵塵 。

在sql 2005/2008下可以這麼做。

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

助人等於自助! [email protected]

帶附加條件的NewID 用法

前天碰到一業務需求,難倒了團隊成員,表結構如下 create table dbo product p id bigint identity 1 1 not null p name nvarchar 255 null categoryid1 int null categoryid2 int null ...

帶附加條件的NewID 用法 downmoon

前天碰到一業務需求,難倒了團隊成員,表結構如下 create table dbo product p id bigint identity 1 1 not null p name nvarchar 255 null categoryid1 int null categoryid2 int null ...

帶附加條件的NewID 用法 downmoon

前天碰到一業務需求,難倒了團隊成員,表結構如下 table dbo product p id bigint identity 1 1 not null p name nvarchar 255 null categoryid1 int null categoryid2 int null categor...