Sql server 2008 使用TSQL随机选择记录总数的百分比
我有一个包含道路参考号和道路长度的表,其中包含RoadID int和RoadLength int列 大约有3000排。使用T-SQL,我需要提取随机选择的道路参考及其长度,其中长度总和占表中所有道路总长度的5%。这是用于随机选择道路的年度道路调查 我正在对SQLServer2008数据库使用T-SQL。尝试了本文中三角形查询的一些变体,但在选择随机行时遇到了困难。我尝试使用order by newID,但结果不正确Sql server 2008 使用TSQL随机选择记录总数的百分比,sql-server-2008,tsql,Sql Server 2008,Tsql,我有一个包含道路参考号和道路长度的表,其中包含RoadID int和RoadLength int列 大约有3000排。使用T-SQL,我需要提取随机选择的道路参考及其长度,其中长度总和占表中所有道路总长度的5%。这是用于随机选择道路的年度道路调查 我正在对SQLServer2008数据库使用T-SQL。尝试了本文中三角形查询的一些变体,但在选择随机行时遇到了困难。我尝试使用order by newID,但结果不正确 如果您能以最有效的方式提供帮助,我们将不胜感激。谢谢我不确定你需要接近总数的5%
如果您能以最有效的方式提供帮助,我们将不胜感激。谢谢我不确定你需要接近总数的5%,但这会让你非常接近:
CREATE TABLE #RoadReference (RoadID INT IDENTITY, RoadLength INT)
INSERT #RoadReference (RoadLength) VALUES (CAST(RAND() * 1000 AS INT))
GO 3000
DECLARE @SampleDistance int
SELECT @SampleDistance = SUM(RoadLength) * .05 FROM #RoadReference
SELECT @SampleDistance AS FivePercentOfTotalRoadLength
SELECT RoadID, SUM(RoadLength) RoadLength
FROM (
SELECT TOP 5 PERCENT *
FROM #RoadReference ORDER BY NEWID()) DataSample
GROUP BY RoadID WITH ROLLUP
ORDER BY RoadLength
凌乱,但似乎有效
--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时,为什么结果看起来不正确?你能提供一个例子吗?我从中改编了这段有用的代码,但我的running total和RoadLength列似乎不符。我是不是在错误的地方使用了NEWID的订单?我使用的是以下内容:Q RoadID、RoadLength、ROW_NUM作为选择RoadID、RoadLength、ROW_NUM作为新ID从zt_Roads订购,RUNNINGTOTALL RoadID、RoadLength、ROW_NUM、RUNNINGTOTALL作为选择*,RunningTotal=从Q中选择SUMRoadLength,其中ROW_NUM是重复的,您是否在FROM子句中为随机样本尝试了tablesample?如果你只需要总数的5%或10%,这将不起作用,但它会让你得到你想要的随机化。谢谢你的帮助@Crosan,非常感谢。我尝试了几个版本,并选择了随机记录,但很难得到一个随机选择,其中总长度加起来占表中所有道路的5%。我想出了一个有点混乱的解决方案,但它似乎有效…