Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2014 Random Value in Group By

I'm trying to figure out how to get a single random row returned per account from a table. The table has multiple rows per account or in some cases just a single row. I want to be able to get a random result back in my select so each day that I run the same statement I might get a different result.

This is basis of the query:

select number, phonenumber
from phones_master with(nolock)
where phonetypeid = '3'

This is a sample result set

number         phonenumber    
--------------------------
4130772,       6789100949    
4130772,       6789257988
4130774,       6784519098
4130775,       6786006874

The column called Number is the account. I'd like to return a single random row. So based on the sample result set above the query should return 3 rows.

Any suggestions would be greatly appreciated. I'm beating my head against the wall with this one.

Thanks

like image 640
Mike S Avatar asked Feb 08 '17 15:02

Mike S


People also ask

How do you assign a random value in SQL?

To create a random integer number between two values (range), you can use the following formula: SELECT FLOOR(RAND()*(b-a+1))+a; Where a is the smallest number and b is the largest number that you want to generate a random number for.

How do you generate unique random numbers in SQL Server?

SQL RAND() example SELECT RAND(); SELECT RAND(5); As you can see, in the first example, the RAND() function generates a random number in decimals between 0 to 1. Each time you execute the statement, it returns different random values.

How do I generate a random number in a column in SQL?

SQL Server has a built-in function that generates a random number, the RAND() mathematical function. The RAND math function returns a random float value from 0 through 1. It can take an optional seed parameter, which is an integer expression (tinyint, smallint or int) that gives the seed or start value.


1 Answers

You can use WITH TIES in concert with Row_Number()

Select Top 1 with ties *
 From  YourTable
 Order by Row_Number() over (Partition By Number Order By NewID())

Returns (for example)

number  phonenumber
4130772 6789257988
4130774 6784519098
4130775 6786006874
like image 91
John Cappelletti Avatar answered Oct 16 '22 09:10

John Cappelletti