-1

I'm asking for a solution without functions or procedures (Permissions problem).

I have a table like this:

where k=number of columns (In reality : k=500)

col1  col2 col3 col4 col5.... col(k)  
10     20   30  -50    60       100

and I need to create a comulative row like this:

col1 col2  col3 col4 col5  ...  col(k)
10    30    60   10   70          X

In Excel, it's a simple shit to make a forumla and drag it but in sql if I have lot of columns, it seems a very clumsy work to add Manually (col1 as col1, col1+col2 as col2, col1+col2+col3 as col3 till colk etc).

Any way of finding a good solution for this problem?

5
  • 1
    This looks like a bad data model. For this model the solution you have come up with is the correct approach. Better would be to change the data model, so you'd have rows instead of columns. Then you'd simply use SUM OVER and be done :-) Jul 25, 2018 at 7:21
  • There is a reason for this - it's more easy to me to do a specific qa on this data.
    – Jordan1200
    Jul 25, 2018 at 7:25
  • Okay. Then the solution you are showing is the way to go. That's a lot of typing, though. You may want to generate your query with some programm, hence. I must admit, though, that I don't understand your model. Why exactly 500 columns? I can imagine a table with twelve columns for twelve months or with four columns for four Hogwarts towers, but what thing has exactly 500 parts? I still think that you should change this data model, so queries are easy to write in general. Jul 25, 2018 at 7:34
  • Thank's. I've changed my data model to rows. Any good idea to get get a comultive row ?
    – Jordan1200
    Jul 25, 2018 at 8:47
  • @Jordan1200 . . . You should ask a new question, with sample data and desired results. Jul 25, 2018 at 11:13

2 Answers 2

0

You say that you've changed your data model to rows. So let's say that the new table has three columns:

  • grp (some group key to identify which rows belong together, i.e. what was one row in your old table)
  • pos (a position number from 1 to 500 to indicate the order of the values)
  • value

You get the cumulative sums with SUM OVER:

select grp, pos, value, sum(value) over (partition by grp order by pos) as running_total
from mytable
order by grp, pos;
-1

If this "colk" is going to be needed/used in a lot of reports, I suggest you create a computed column or a view to sum all the columns using k = cola+colb+...

There's no function in sql to sum up columns (ex. between colA and colJ)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.