Skip to content

Instantly share code, notes, and snippets.

@stuartlynn
Last active April 12, 2016 20:15
Show Gist options
  • Save stuartlynn/c8647a97c8e20e5e0466 to your computer and use it in GitHub Desktop.
Save stuartlynn/c8647a97c8e20e5e0466 to your computer and use it in GitHub Desktop.
Postgresql function max_of

max_of

returns the label for the max column of a row for each row

Say you have a table cat_dogs:

no_cats no_dogs
1 10 0
2 5 6
3 1 2
SELECT max_of(Array[no_cats,no_dogs], Array["cats","dogs"]) AS dominant_animal, * 
FROM cat_dogs

the function will return

no_cats no_dogs dominant_animal
1 10 0 cats
2 5 6 dogs
3 1 2 dogs
select max_of(Array[1,2,3],Array['one','two','three'])
create or replace function max_of(vals numeric[], names text[]) returns text as $$
DECLARE
max_val numeric;
BEGIN
max_val = (select max(a) from unnest(vals) a);
for i in 0..array_length(names,1) loop
if vals[i] = max_val then
return names[i];
end if;
end loop;
END
$$
LANGUAGE plpgsql
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment