B
B
beginer1232016-09-28 21:31:12
SQL
beginer123, 2016-09-28 21:31:12

Sql sum values ​​in 100 columns?

There are columns with numbers
column1,column2,column3...........,column100 It is
necessary to calculate the sum of all 100 columns It is
natural to write
select column1+column2+column3+....+column100 is not an option
What is the way to do this( in a loop there or something else) I
use Sqlite

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alex Wells, 2016-09-28
@Alex_Wells

Just:
And the SQL query itself must be assembled by some kind of builder or string builder. I don't think this will be a problem.

R
Roman Mirilaczvili, 2016-09-28
@2ord

It's just some kind of unthinkable database structure ... I won't ask why.
You can programmatically compose an SQL query like the example below in Ruby language,

select_clause = ""
for i in (1..99) do
  select_clause += "column" + i.to_s + "+"  # i.to_s конвертирует число в строковое представление
end
select_clause += "column100"
sql_statement = "SELECT " + select_clause + " FROM table_name"

I
igruschkafox, 2016-09-29
@igruschkafox

I support that the database structure is unthinkable
, but I would make a calculated column with a stored value

R
rll, 2016-11-01
@rll

Without the use of programming languages, purely using the SQLITE command line, you can do this:
Let's say this is the initial data (like the author of the request?):

CREATE TABLE if not exists mytable (id integer, column1 integer, column2 integer, column3 integer);
insert into mytable values (1, 54, 88, 99);
insert into mytable values (2, 22, 12, 778);
insert into mytable values (3, 0, 123, 88);
insert into mytable values (4, 7, 42, 35);
insert into mytable values (5, 5, 47, 23);

Then the sum of the columns can be obtained like this:
create table if not exists temp(a text, b text, c text, d text, e text, f text);

.out temp.txt
pragma table_info('mytable');
.out stdout

.import temp.txt temp

.out temp.txt
select 'select ' || group_concat(b, '+') || ' as resultColumn from mytable;' from temp where b like 'column%';
.out stdout
drop table temp;

.read temp.txt

Commands can be slipped into SQLITE in the form of a script, then you don’t even need to type them.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question