Jayesh Babu
Jayesh Babu

Reputation: 1449

sum of values in each column in a database table

I have a table like this:

enter image description here

Table name is List. I have to get sum of each column. I cannot give this query:

SELECT SUM(jayesh,murali,jins) from List;

because the columns are added dynamically. Column names are given as user input. Is there any other code to do this..?

Upvotes: 0

Views: 779

Answers (2)

mayabelle
mayabelle

Reputation: 10014

Not saying that any of this is or is not a good idea because no context was provided, but...

Sum of all columns combined for all records (one sum for entire table):

SELECT SUM(jayesh+murali+jns)
FROM List

Sum of all columns for each record (one sum for each row): (This option requires having an id column to group by so that you can determine how to group the rows)

SELECT
    ID,
    SUM(jayesh+murali+jns)
FROM List
GROUP BY ID

Sum of each column separately for all records (one sum for each column):

SELECT
    SUM(jayesh), 
    SUM(murali), 
    SUM(jns)
FROM List

I would also recommend reconsidering your design in adding dynamic columns based on user input. This is generally not a good idea, certainly not for this case. Read more here: http://www.sommarskog.se/dynamic_sql.html

Upvotes: 1

MPelletier
MPelletier

Reputation: 16677

If you want the sum in each column:

SELECT SUM(jayesh), SUM(murali), SUM(jns) from List;

Upvotes: 1

Related Questions