Если вы хотите попробовать динамический sql для этого?
Вот пример фрагмента для MySql:
-- Adding a test table
drop table if exists test_dynamic;
create table test_dynamic (ID int auto_increment primary key, Nme varchar(30), Py int, Cm int, Mt int);
-- Some sample data
insert into test_dynamic (Nme, Py, Cm, Mt) values
('johny',68,70,66),
('Harry',86,76,90),
('johny',18,72,66);
-- Build a string for the aggregations
set @Sums := (select group_concat(concat(' SUM(', column_name, ') as ', column_name)) as sums
from information_schema.columns
where table_schema = database()
and table_name = 'test_dynamic'
and data_type = 'int'
and column_key != 'PRI');
-- Stick it to a string for the select
set @DynSql := concat('select
Nme,
', @Sums, '
from test_dynamic
group by Nme
order by Nme');
-- Run the created dynamic sql string
PREPARE stmt FROM @DynSql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Возвращает:
Nme Py Cm Mt
---- -- -- --
Harry 86 76 90
johny 86 142 132