凌乱,但它似乎工作
--Create a temp table and add a random number column
CREATE TABLE #Roads(ROW_NUM int, RoadID int, RoadLength int)
--Populate from zt_Roads table and add a random number field
INSERT #Roads (ROW_NUM , RoadID , RoadLength )
(SELECT ROW_NUMBER() OVER (ORDER BY NEWID()),
RoadID,
RoadLength
from zt_Roads)
go
--Calcualte 5% of the TOTAL length of ALL roads
declare @FivePercent int
SELECT @FivePercent = ROUND(Sum(IsNULL((RoadLength ),0))*.01,0) from zt_Roads
print 'One Percent of total length = '
Print @FivePercent
--Select a random sample from temp table so that the total sample length
--is no more than 5% of all roads in table
; with RandomSample as
(SELECT top 100 percent
ROW_NUM,
RoadID,
RoadLength,
RoadLength+
COALESCE((Select Sum(RoadLength) from #Roads b
WHERE b.ROW_NUM < a.ROW_NUM),0) as RunningTotal
From #Roads a
ORDER BY ROW_NUM)
Select * from RandomSample WHERE RunningTotal <@FivePercent
Drop table #Roads