Monday, January 5, 2015

Random numbers in TSQL queries

Say you wan to generate test and control groups directly in the results of a query, with each row being in either a control group or the test group.


Here’s one way to roll a random number between 0 and 1:

select ABS(CONVERT(BIGINT,CONVERT(BINARY(8), NEWID()))) % 2


Here’s how to roll a random number between 0 and 2:

select ABS(CONVERT(BIGINT,CONVERT(BINARY(8), NEWID()))) % 3


0 and 5:

select ABS(CONVERT(BIGINT,CONVERT(BINARY(8), NEWID()))) % 6


0 and 18:

select ABS(CONVERT(BIGINT,CONVERT(BINARY(8), NEWID()))) % 19





No comments:

Post a Comment