Quantcast
Viewing all articles
Browse latest Browse all 9

randomize in T-SQL

I thought this question was answered, I guess not...

Here is an example you can run through multiple times:

CREATE TABLE #City
(
CityName	VARCHAR(40) NOT NULL,
ProvinceCode	INT NOT NULL
);
GO

INSERT INTO #City(CityName, ProvinceCode) VALUES ('City1',1),('City2',2),('City3',3),('City4',1),('City5',1),('City6',1),('City7',2),('City8',2),('City9',2),('City10',3),('City11',3);
GO

;WITH RandomCityWithGroup AS
(
SELECT CityName, ProvinceCode, ROW_NUMBER() OVER (PARTITION BY ProvinceCode ORDER BY NEWID() ASC) AS RID FROM #City
)
SELECT CityName, ProvinceCode FROM RandomCityWithGroup WHERE RID = 1 ORDER BY ProvinceCode ASC /* select 1 row from each group randomly */
GO

DROP TABLE #City;
GO

-Sean


Sean Gallardy | Blog | Twitter


Viewing all articles
Browse latest Browse all 9

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>