Search code examples
sqlsql-servert-sqlgroup-byrollup

Modifying Roll Up SQL


I have this 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

This Code will Roll up a count, and provide a percentage for that particular point in the roll up.

My Question: This script required hard-coding the initial values. How exactly do I do this with a SQL statement pulling in values from a table in the SQL database?

In other words, From:

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

Drop the "values" piece from below and substitute it within "select [field names] from [Table Name


Solution

  • You are looking for insert from select syntax

    INSERT INTO @table (col1, col2) 
    select col1, col2 
      from Sourcetable --replace it with your sourcetable name
    

    Also if you are using sql server 2012+, then here is a efficient way to calculate running total

    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