我从另一篇很老的帖子中得到了这段代码。除了我传递92k记录外,代码完美无缺。当我用几条记录测试它时,结果是正确的,但是当我用完整的数据集进行测试时,它会给出错误。
SELECT Part_Number, SUM(TL52) AS T12
into #pdtemp
FROM TBLPARTDATA
GROUP BY NAV_PN
ORDER BY 2 DESC
CREATE NONCLUSTERED INDEX [#pdtemp_NAV_PN] ON [dbo].[#pdtemp] ([NAV_PN] ASC)
WITH (
PAD_INDEX = OFF
, STATISTICS_NORECOMPUTE = OFF
, SORT_IN_TEMPDB = OFF
, IGNORE_DUP_KEY = OFF
, DROP_EXISTING = OFF
, ONLINE = OFF
, ALLOW_ROW_LOCKS = ON
, ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]
CREATE NONCLUSTERED INDEX [#pdtemp_T12] ON [dbo].[#pdtemp] ([T12] ASC)
WITH (
PAD_INDEX = OFF
, STATISTICS_NORECOMPUTE = OFF
, SORT_IN_TEMPDB = OFF
, IGNORE_DUP_KEY = OFF
, DROP_EXISTING = OFF
, ONLINE = OFF
, ALLOW_ROW_LOCKS = ON
, ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]
DECLARE @percent DECIMAL (20, 16)
SET @percent = 0.8
SELECT DISTINCT s.Part_Number,
s.t12,
s.t12 + Coalesce(SUM(s2.t12) OVER (PARTITION BY s.t12), 0)
runningsum
into #sums
FROM #pdtemp s
LEFT JOIN #pdtemp s2
ON s.t12 < s2.t12
SELECT NAV_PN,
t12,
runningsum,
CAST(runningsum AS DECIMAL(15, 5)) / tots.total
running_percent,
Row_number() OVER (ORDER BY runningsum, Part_Number ) rn
into #percents
FROM #sums,
(SELECT SUM(t12) total
FROM #pdtemp) AS tots
SELECT p.Part_Number,
p.t12,
p.running_percent,
p.rn
FROM #percents p
CROSS JOIN (SELECT MAX(rn) rn
FROM #percents
WHERE running_percent = @percent) exactpercent
LEFT JOIN (SELECT MAX(rn) rn
FROM #percents
WHERE running_percent <= @percent) underpercent
ON p.rn <= underpercent.rn
OR ( exactpercent.rn IS NULL
AND p.rn <= underpercent.rn + 1 )
WHERE
underpercent.rn is not null or p.rn = 1
我还尝试运行此操作,其中临时表是子选择并且它不运行。