Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically calculate the sums of many columns in a GROUP?

In the table below, I have a variable number of columns, and that number is in the 1000s. I need to sum all the values of each of the 1000 columns grouped by the person's name. So, smith's total test_score_1, total test_score_2,...total test_score_1000. And then Jackson's total test_score_1, total test_score_2,...total test_score_1000.

I don't know the number of 'test_score_n' columns beforehand and they are always changing.

So given this table:

name      test_score_1 test_score_2 ...  test_score_1000
  smith        2              1                 0
  jackson      0              3                 1
  jackson      1              1                 2
  jackson      3              0                 3
  smith        4              5                 1

How can I produce the table below?

name      test_score_1 test_score_2 ...  test_score_1000
  smith        6              6                1
  jackson      4              4                6
like image 915
user798719 Avatar asked Dec 07 '22 17:12

user798719


1 Answers

SQL to generate the SQL

DECLARE @generatedSQL nvarchar(max);

SET @generatedSQL = (

SELECT
    'SELECT ' + 
    SUBSTRING(X.foo, 2, 2000) + 
    'FROM ' + 
    QUOTENAME(SCHEMA_NAME(t.schema_id)) + '.' + QUOTENAME(t.name) +
    ' GROUP BY name' --fix this line , edited
FROM
    sys.tables t
    CROSS APPLY 
    (
    SELECT
        ', SUM(' + QUOTENAME(c.name) + ')'
    FROM 
        sys.columns c 
    WHERE 
        c.object_id = t.object_id
        AND
        c.name <> 'Name'
    FOR XML PATH('')
    ) X (foo)
WHERE
    t.name = 'MyTable'
 );

EXEC (@generatedSQL);
like image 57
gbn Avatar answered Jan 13 '23 15:01

gbn