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