Created
February 14, 2019 11:35
-
-
Save abevieiramota/6a6beca86635f756d9ef8dd6fc14471f to your computer and use it in GitHub Desktop.
retorna a coluna com maior valor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
with tabela as ( | |
select format('%s.%s', quote_ident(nsp.nspname), quote_ident(t.tablename)) as tablename, c.oid | |
from pg_catalog.pg_tables t | |
inner join pg_catalog.pg_class c on c.relname = t.tablename | |
inner join pg_catalog.pg_namespace nsp on nsp.nspname = t.schemaname and nsp.oid = c.relnamespace | |
where t.tablename = :tablename and nsp.nspname = :schemaname | |
), cols_dif_resultado as ( | |
select | |
t.tablename, att.attname as col | |
from pg_catalog.pg_attribute att | |
inner join tabela t on t.oid = att.attrelid | |
where att.attnum > 0 and att.attname not in ('COLUNAS', 'QUE', 'EU', 'NÃO', 'QUERO', 'CONSIDERAR') | |
) | |
select format('with aux as ( | |
select t.*, n.col | |
from %s t, (values %s) as n(col) | |
), aux2 as ( | |
select | |
id, | |
col, | |
rank() over(partition by id order by | |
case col %s | |
end desc | |
) n | |
from aux | |
) | |
select id, col | |
from aux2 | |
where n = 1', | |
c.tablename, | |
string_agg(format('(''%s'')', c.col), ','), | |
string_agg(format('when ''%s'' then %s', c.col, c.col), E'\n')) | |
from cols_dif_resultado c | |
group by c.tablename; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment