tags:

views:

429

answers:

3

I have a table that looks like this:

id    test1    test2    test3    test4 ... test200
1      90       87       85        86        70
2      100      95       83        92        80
.
.
18000

I know there are standard operations to perform sums and averages on a single column and multiply the value of two columns together but is it possible to do it across all columns in a row with a given id? If its not clear, I want to do something like this across rows instead of across columns. Thanks

+2  A: 

How about:

select id, sum(test1 + test2 + ...) as summation
group by id

Is the problem that you have so many columns? This solution doesn't handle many columns smoothly.

Ryan Anderson
The sum should work, but he probably should normalize that table. This is going to be painful if he needs to add a column every time he add a test.
Eric Hogue
Good point ehogue. Didn't realize the columns are for test data.
Ryan Anderson
A: 

There might be some contorted SQL to work on the contents of the whole row (I doubt that), but you still have to specify the column names, otherwise you'd have the ID numbers included in the calculation.

Nouveau
+6  A: 

You might be better off redesigning the table so that it does not have 200 columns.

e.g.

Id  testnum  score
1    1        90
1    2        87
...
2    1        100
2    2        95
...
180000

Now you can do a query like this:

select sum(score) as totalscore
from mynewtable
where id=1
Vincent Ramdhanie
+1 - I would recommend not making crosstab tables as well
Knobloch
Okay I think this will probably be the best. I was trying to figure out a way to redesign the table and this should probably do it. Thanks!
Jack L.
Also, is there an easy way to do this? The table I created was an imported csv...
Jack L.
There are easy ways e.g. with a little scripting code (Perl, Python, whatever), I can't think of one in pure SQL though -- maybe open another question clarifying what tools are acceptable.
Alex Martelli
Right I realized it was a silly question. I ended up using Perl. Thanks again.
Jack L.
I am able to get the sum and averages of all tests when specifying an id, but how do I multiply the test results of separate Ids? I want to do this to get a correlation coefficient between two Ids (students)
Jack L.
You are probably going to have to use nested queries to accomplish this correlation that you want.
Vincent Ramdhanie