Skip to content

Instantly share code, notes, and snippets.

@deminoth
Created December 27, 2017 08:36
Show Gist options
  • Save deminoth/e4a2c3891c7dd705241c8a603c0f2312 to your computer and use it in GitHub Desktop.
Save deminoth/e4a2c3891c7dd705241c8a603c0f2312 to your computer and use it in GitHub Desktop.
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'select name, ''',
c.column_name,
''' as word, ',
c.column_name,
' as qty
from bird'
) SEPARATOR ' UNION ALL '
) INTO @sql
FROM information_schema.columns c
where c.table_name = 'bird'
and c.column_name not in ('name')
order by c.ordinal_position;
SET @sql
= CONCAT('select ANY_VALUE(word), count(word) from (
select name, word, qty,
(@num:=if(@name = `name`, @num +1, if(@name := `name`, 1, 1))) row_number
from
(', @sql, ') x order by name, qty desc
) x where x.row_number < 2 group by word');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment