0

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;
1
  • Wrte a dynamic SQL statement based on the tableName and ColumnName to get the min max... Commented May 8, 2016 at 16:48

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Throwing a syntax error on the SEPARATOR line. I obviously replaced the actual table name in the 2 places referenced - are any other changes needed?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.