前天碰到一业务需求,难倒了团队成员,
表结构如下:





[CategoryID3] [int] NULL,
[P_SingleIntro] [nvarchar](200) NULL,






需要随机列出表中每位用户(loginid)的一个产品,每次列出时随机值不重复。
于是考虑用newid()


结果每次取到的P_ID都是相同的! 不符合需求
再修改如下:






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
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