Selecting a Random Subset in SQL (Sybase Server IQ)

倾然丶 夕夏残阳落幕 提交于 2019-12-23 17:21:08

问题


I'm trying to select a random subset of records using either rand() or newid(), but any time I run the following, I always get the same results back:

SELECT *,rand() as rid
INTO #mytable
FROM othertable

select top 10 * from #mytable order by rid

I've tried every variation of this, but it seems that sybase server iq always returns the same rand() value when I do it like the above. When I try to do

SELECT * FROM othertable order by newid()

I get an error saying it's illegal to use newid() in the order by.

Any suggestions?


回答1:


In Sybase T-SQL, The NEWID() system function generates human-readable, globally unique IDs. Include the NEWID() system function in the ORDER BY clause when issuing the SELECT statement on the target table.

Usage:

SELECT top 10 id from TABLE order by NEWID();



回答2:


Random values in the IQ engine are deterministic, force a query through the ASA engine like below (Warning: it is slow if you have many rows).

select (select rand() as rnd) from mytable



回答3:


You can get random effect by using row_number() function and current time values. Try something like this:

with q as (
    SELECT
        *,
        row_number() over (order by cPublisher) n, -- getting row number
        DATEPART(ms, now()) t -- getting current ms value
    FROM 
        #mytable
)

select top 10
    *
from
    q
order by 
    -- order by some combination t and n, for example t * n and sort it like char
    cast(t * n as char)


来源:https://stackoverflow.com/questions/9792676/selecting-a-random-subset-in-sql-sybase-server-iq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!