尽管您必须扩展答案以计算运行百分比,但您几乎有一个关于运行总计的问题的副本。我建议通读链接问题的答案(注意 MSSQL 2012 有语法,万岁!),因为它们比我下面的建议更深入。SUM...OVER
对于您的情况,您可以执行以下操作来获得运行百分比:
DECLARE @table TABLE(col1 INT, col2 FLOAT);
INSERT INTO @table (col1, col2)
VALUES (1, 500), (2, 499), (3, 200), (4, 50), (5, 10), (6, 5)
DECLARE @col2total FLOAT = (SELECT SUM(col2) FROM @table)
-- Using subqueries
SELECT col1,
col2,
(SELECT SUM(col2) FROM @table sub WHERE sub.col1 <= base.col1)
/ @col2total
* 100 AS RunningPercentage
FROM @table base
ORDER BY col1
-- Using cross join
SELECT t1.col1,
t1.col2,
SUM (t2.col2) RunningTotal,
SUM (t2.col2) / @col2total * 100 RunningPercentage
FROM @table t1 CROSS JOIN @table t2
WHERE t1.col1 >= t2.col1
GROUP BY t1.col1, t1.col2
ORDER BY t1.col1
有了这个,你应该很容易以任何你喜欢的方式获得顶部或底部的 80%。