PostgreSQL - Truncating A Date Within Age Function

跟風遠走 提交于 2019-12-11 04:50:29

问题


I have the following query:

SELECT usersid as user,
(age(creationtime)) as account_days
FROM users

which outputs users (an integer) and account_days which uses the timestamp to output the age (i.e. 58 days, 2:31:31.387746).

I want the output to just say 58, instead of 58 days, 2:31:31.387746. How would I go about this? I attempted

SELECT usersid as user,
EXTRACT(day FROM(age(creationtime))) as account_days
FROM users

but it changes the output to a number that doesn't tie out.

Im using version PostgreSQL 9.2.4 on x86_64-unknown-linux-gnu, compiled by gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3, 64-bit


回答1:


Sounds looks like you want to look into justify_interval() and date_trunc():

denis=# select justify_interval(date_trunc('day', '58 days, 2:31:31.387746'::interval));
 justify_interval 
------------------
 1 mon 28 days
(1 row)

http://www.postgresql.org/docs/current/static/functions-datetime.html




回答2:


Date subtraction

You can get the number of days by casting both operands to date then subtracting, instead of using the age function that returns a justified interval:

SELECT current_date - creationtime::date
FROM ...
WHERE ...

Partial days will be rounded down and the integer number of days returned.

eg:

select current_date - (current_timestamp - INTERVAL '1 month 28 days, 2:31:31.387746')::date;

to_char's DDD format specifier

Alternately you can use the format specifier DDD for to_char, with the FM format modifier to remove the leading zeroes:

 select to_char(age( current_timestamp - INTERVAL '1 month 28 days, 2:31:31.387746'), 'FMDDD');

This will still work for > 1 year:

regress=> select to_char(age( current_timestamp - INTERVAL '8 year 1 month 28 days, 2:31:31.387746'), 'FMDDD');
 to_char 
---------
 2936
(1 row)



回答3:


Just needed something similar, the solution should be:

SELECT (NOW()::date - creationtime::date) AS account_days FROM users

Output is a single integer



来源:https://stackoverflow.com/questions/16990161/postgresql-truncating-a-date-within-age-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!