我有这个SQL:
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
此代码将汇总一个计数,并为汇总中的特定点提供百分比。
我的问题: 该脚本需要对初始值进行硬编码。我如何使用从SQL数据库中的表中提取值的SQL语句来完成此操作?
换句话说,来自:
INSERT INTO @table (col1, col2)
VALUES (1, 500), (2, 499), (3, 200), (4, 50), (5, 10), (6, 5)
删除&#34;值&#34;从下面分割并在&#34中替换它;从[表名称
中选择[字段名称]答案 0 :(得分:0)
您正在寻找选择语法的插入
INSERT INTO @table (col1, col2)
select col1, col2
from Sourcetable --replace it with your sourcetable name
此外,如果您使用sql server 2012+
,则此处是计算运行总计
SELECT col1,
col2,
RunningTotal = Sum(col2)OVER(ORDER BY col1),
RunningPercentage = Sum(col2)OVER(ORDER BY col1) / Sum(col2)OVER() * 100
FROM @table base
ORDER BY col1