 SELECT IF( monthly = '1', IF( ( 1 + ((year_end - year_ini) * 12) + (month_end - month_ini) ) = nro_tables, 'Ok', 'NotOk' ), IF( (nro_tables - (year_end - year_ini)) = 1, 'Ok', 'NotOk' ) )                               AS `control`, IF( month_ini > '0', month_ini, '00' )                               AS `month_ini`, IF( month_end > '0', month_end, '00' )                               AS `month_end`, periodo.`pais`                  AS `pais`, periodo.`tipo`                  AS `tipo`, LPAD(periodo.`subtipo`, 2, '0') AS `subtipo`, periodo.`operation`             AS `operation`, periodo.`monthly`               AS `monthly`, periodo.`year_ini`              AS `year_ini`, periodo.`year_end`              AS `year_end`, periodo.`nro_tables`            AS `nro_tables`, 'TABLES' AS `source` FROM (SELECT TABLE_SCHEMA AS pais, SUBSTR(TABLE_NAME, 4, 2) AS tipo, SUBSTR(TABLE_NAME, 7, 2) AS subtipo, SUBSTR(TABLE_NAME, 10, 2) AS operation, TABLE_NAME REGEXP '^([a-z]{2})_([a-z]{2})_([0-9]{2})_(IM|EX)_([0-9]{4})_([0-9]{2})$' AS monthly, MIN(SUBSTR(TABLE_NAME, 13, 4)) AS year_ini, MAX(SUBSTR(TABLE_NAME, 13, 4)) AS year_end, SUBSTR( MIN( CONCAT( SUBSTR(TABLE_NAME, 13, 4), SUBSTR(TABLE_NAME, 18, 2) ) ), 5, 2 ) AS month_ini, SUBSTR( MAX( CONCAT( SUBSTR(TABLE_NAME, 13, 4), SUBSTR(TABLE_NAME, 18, 2) ) ), 5, 2 ) AS month_end, COUNT(*) AS nro_tables FROM information_schema.`TABLES`/* `TABLES` | `VIEWS` */ WHERE TABLE_NAME REGEXP '^([a-z]{2})_([a-z]{2})_([0-9]{2})_(IM|EX)_([0-9]{4})$' OR TABLE_NAME REGEXP '^([a-z]{2})_([a-z]{2})_([0-9]{2})_(IM|EX)_([0-9]{4})_([0-9]{2})$' GROUP BY pais, tipo, subtipo, operation ) AS periodo WHERE pais LIKE 'CO' AND tipo = 'dt' AND subtipo = '00' AND operation = 'im';