日期:2014-05-17  浏览次数:20958 次

ACCESS中随机读取X条记录但不能有重复记录的问题
举例说表中有100条记录,我想从中随机取出NUM条,这样可以实现:
select   top   "&num& "   mobile   from   Mobile_MO   where   Adddate> # "&start_date& "#   and   Adddate <# "&end_date& "#   ORDER   BY   Rnd(id)

这样是可以随机取出NUM条,但是会有重复的MOBILE,我现在想取出的NUM条记录都是唯一的MOBILE
select   distinct   top   "&num& "   *   from   Mobile_MO   where   Adddate> # "&start_date& "#   and   Adddate <# "&end_date& "#   ORDER   BY   Rnd(id)

这样写就报错了,说DISTINCT不能和RND一起使用,请问大家要怎么实现我的需求?

------解决方案--------------------
一句SELECT可能不能实现吧,期特高手……
------解决方案--------------------
mark
------解决方案--------------------
intMin = objConn.Execute( "select min(id) from Mobile_MO where Adddate> # "&start_date& "# and Adddate <# "&end_date& "# ")(0)
intMax = objConn.Execute( "select Max(id) from Mobile_MO where Adddate> # "&start_date& "# and Adddate <# "&end_date& "# ")(0)


Function GetRan(iMIn, iMax, iNum)
Dim i
Dim iRnd
Dim strRnd

Randomize
For i = 1 To iNum
iRnd = Int(Rnd() * (iMax - iMIn + 1)) + iMIn
If strRnd = " " Then
strRnd = CStr(iRnd)
Else
If InStr(strRnd, CStr(iRnd)) Then
iNum = iNum + 1
Else
strRnd = strRnd & ", " & iRnd
End If
End If
Next
GetRan = strRnd
End Function

strList = GetRan(intMIn, intMax, intNum) '获得随机数字符串

select * from Mobile_MO where Adddate> # "&start_date& "# and Adddate <# "&end_date& "# and id in ' "& strList & " ' "
------解决方案--------------------
不知道ACCESS有没有NEWID()?
------解决方案--------------------
楼上的 id 不一定就是递增的噢 ...

万一 id 如下列这样 2 5 6 7 21 22 23 ... 是不是不行拉?
------解决方案--------------------
作個記號,隨時關注
------解决方案--------------------
如果只取mobile 字段,可以用GROUP BY mobile,但是不知道能不能和RUN联用

------解决方案--------------------
"select distinct top "&num& " mobile from (select mobile from Mobile_MO where Adddate> # "&start_date& "# and Adddate <# "&end_date& "# ORDER BY Rnd(id)) "
------解决方案--------------------
偶也来学习一下。
------解决方案--------------------
学习一下```
------解决方案--------------------
"select distinct top 10 mobile
from (
select mobile
from Mobile_MO
where Adddate> # "&start_date& "# and Adddate <# "&end_date& "# ORDER BY Rnd(id)
) "
这样不就行了