In C I can switch between int and char to build a list of sequential integers and then convert them to ASCII characters that will be sequential according to the alphabet.
Is there a way to do this in postgres to get a column with row values “A”,”B”,”C” etc…?
the only way I can think of would be to start with a SERIAL
column of ints and then write a CASE
to set each row individually. The Tables big enough that it would be much preferred to do this automatically somehow.
Advertisement
Answer
Take a look here: Calculate MS Excel column name from its number in PostgreSQL
CREATE FUNCTION excel_column(col integer) RETURNS text AS $BODY$ WITH RECURSIVE t(n, out) AS ( SELECT col/26-(col%26=0)::int, chr((col-1)%26 + 65) UNION ALL SELECT n/26-(n%26=0)::int, chr((n-1)%26 + 65) || out FROM t where n>0 ) SELECT out FROM t where n=0; $BODY$ LANGUAGE sql IMMUTABLE LEAKPROOF STRICT;
Usage:
select excel_column(x) from generate_series(1,800) x;
Result:
A B .. AA AB .. ZZ AAA .. ADT