sql >> Base de Datos >  >> RDS >> PostgreSQL

Dos preguntas para formatear la marca de tiempo y el número usando postgresql

Parece que las funciones to_timestamp() y to_char() lamentablemente no son perfectos. Si no puede encontrar nada mejor, use estas soluciones alternativas:

with example_data(d) as (
    values ('2016-02-02')
    )
select d, d::timestamp || '.0' tstamp
from example_data;

     d      |        tstamp         
------------+-----------------------
 2016-02-02 | 2016-02-02 00:00:00.0
(1 row)

create function my_to_char(numeric)
returns text language sql as $$
    select case 
        when strpos($1::text, '.') = 0 then $1::text
        else rtrim($1::text, '.0')
    end
$$;

with example_data(n) as (
    values (100), (2.00), (3.34), (4.50))
select n::text, my_to_char(n)
from example_data;

  n   | my_to_char 
------+------------
 100  | 100
 2.00 | 2
 3.34 | 3.34
 4.50 | 4.5
(4 rows)

Consulte también:Cómo eliminar el punto en to_char si el número es un número entero