Dylan
Dylan

Reputation: 151

MySQL min and max of each column

I can run the following to dynamically identify all decimal fields in table with many columns:

SELECT COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='tbl_name' AND DATA_TYPE = 'decimal'

How would I pull the min and max value for each of those fields? e.g. final output like:

COLUMN_NAME  DATA_TYPE  MIN_VAL  MAX_VAL
a            decimal    4        22
b            decimal    18       5593
c            decimal    1        299

UPDATE:

Here is the final syntax I used to get this working. Maybe I missed an easier way but this is working, so thanks to Gordon Linoff for the answer.

set @sql = concat('SELECT ', @cols, ' FROM ', @t);

SELECT @sql := GROUP_CONCAT(REPLACE(REPLACE(@sql, @cols,
                                            CONCAT('"', COLUMN_NAME, '" as TheCol', ', ', '"', DATA_TYPE, '" as TheDType', ', ',
                                                   'MIN(', COLUMN_NAME, ') as TheMin, MAX(', COLUMN_NAME, ') as TheMax'
                                                  )
                                           ),
                                    @t, 'tbl_name') SEPARATOR ' union all '
                            )              
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='tbl_name' AND DATA_TYPE = 'decimal';

prepare s from @sql;
execute s;
deallocate prepare s;

Upvotes: 0

Views: 1052

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269773

You need to use dynamic sql:

set @sql = 'SELECT @cols FROM @t';

SELECT @sql := GROUP_CONCAT(REPLACE(REPLACE(@sql, @cols,
                                            CONCAT(COLUMN_NAME, ', ', DATA_TYPE, ', ',
                                                   'MIN(', COLUMN_NAME, '), MAX(', COLUMN_NAME, ')'
                                                  )
                                           ),
                                    @t, 'tbl_name') SEPARATOR ' union all '
                            )              
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='tbl_name' AND DATA_TYPE = 'decimal';

prepare s from @sql;
execute s;
deallocate prepare s;

Upvotes: 2

Related Questions