凌亂,但它似乎工作
--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
當使用Order By NewID時,爲什麼結果看起來不正確?你能提供一個例子嗎? – 2013-03-21 12:17:15
我從http://www.sqlservercentral.com/Forums/Topic793008-149-1.aspx調整了這個有用的代碼,但我的運行總數和RoadLength列似乎不相符。我是否在錯誤的地方使用了NEWID()的Order?我現在用的是以下幾點: – Trigpoints 2013-03-21 12:38:04
與Q(RoadID,RoadLength,ROW_NUM) \t \t AS \t \t \t \t \t(SELECT RoadID,RoadLength,ROW_NUMBER()OVER(ORDER BY NEWID()) \t \t \t FROM zt_Roads ), \t \t \t \t \t RunningTotal(RoadID,RoadLength,ROW_NUM,RunningTotal) \t \t \t \t \t AS \t \t \t \t(SELECT *,RunningTotal =(SELECT SUM(RoadLength)FROM q其中ROW_NUM <= A.ROW_NUM) \t \t \t \t自Q AS A) \t \t \t \t \t \t SELECT \t * FROM RunningTotal \t \t \t \t WHERE \t ROW_NUM <=(SELECT MIN(ROW_NUM) \t \t FROM RunningTotal \t \t WHERE RunningTotal> 6000)--test使用6000,理想地希望在這裏使用的參數來計算5%到總長度 – Trigpoints 2013-03-21 12:38:49