修改汇总 SQL

Modifying Roll Up SQL

我有这个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 数据库中的 table 中提取值?

换句话说,发件人:

INSERT INTO @table (col1, col2) 
VALUES (1, 500), (2, 499), (3, 200), (4, 50), (5, 10), (6, 5)

从下方删除 "values" 部分并将其替换为“select [field names] from [Table Name

您正在寻找来自 select 语法的插入

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