Just a day ago I received email from reader how to get single random number for range of rows of any table. The question was not very clear to me so I had asked him to send me question in simpler words. He sent me question back in simple words. Let us understand this problem using database AdventureWorks.
In AdventureWorks database we have table called Person.Address. How to get single random number generated for PostalCode ’98011′ and another single random number for PostalCode ’98033′. So far I have never received scenario like this. I had previously faced situation where I had to genrate new random number for each row of table.
Let us understand two scenarios here.
Different Random Number for Different Rows (Using NEWID())
USE AdventureWorks
GO
SELECT TOP 5 NEWID() AS GUID, *
FROM Person.Address
GO
Single Random Number for Set of Rows (Using RAND())
USE AdventureWorks
GO
SELECT TOP 5 RAND() AS RandomNumber, *
FROM Person.Address
WHERE PostalCode = '98011'
GO
SELECT TOP 5 RAND() AS RandomNumber, *
FROM Person.Address
WHERE PostalCode = '98033'
GO
Watch a 60 second video on this subject
I have sent email back to my reader asking his need for single random number for set of rows in real world example but I have not received his reply. I want to bring this to my readers and ask them what do you think can be usage of this concept in real life application.
Reference : Pinal Dave (http://blog.SQLAuthority.com)
