Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating difference of dates In Postgresql

I'm trying to find out the time between certain fields in my tables. However cause I'm using Postgresql :(( I can't use the DATEDIFF function. I can't find any clear guides/ tutorials on the net which shows how to do a similar thing in Postgres so I need help doing the same thing but in Postgres

I'm assuming this query would work if I was using a RDBMS that supported the DATEDIFF function so basically my question is how can I change this so it works using features provided by Postgresql?

SELECT Question.ID, 
Question.Status, COUNT (qUpdate.ID)  AS NumberofUpdates,
DATEDIFF (Question.LoggedTime,MIN(qUpdate.UpdateTime)) AS TimeBeforeFirstUpdate,
DATEDIFF(Question.LoggedTime, MAX(qUpdate.UpdateTime)) AS TimeBeforeLastUpdate
FROM qUpdate
LEFT JOIN Question ON qUpdate.qID=Question.ID
WHERE Question.Status = 'closed' AND qUpdate.Update NOT NULL
GROUP BY Question.Status, Question.ID, Question.LoggedTime;

If you need more info or any clarification I'll responsd ASAP.

like image 579
Jimmy Avatar asked Apr 08 '12 19:04

Jimmy


People also ask

How does Postgres calculate date difference?

In PostgreSQL, if you subtract one datetime value (TIMESTAMP, DATE or TIME data type) from another, you will get an INTERVAL value in the form ”ddd days hh:mi:ss”. So you can use DATE_PART function to extact the number of days, but it returns the number of full days between the dates.


1 Answers

You don't need a "datediff" function.

Just subtract the two dates:

Question.LoggedTime - MIN(qUpdate.UpdateTime)

In case you don't know, but all that is documented online:
http://www.postgresql.org/docs/current/static/functions-datetime.html

like image 115
a_horse_with_no_name Avatar answered Sep 21 '22 19:09

a_horse_with_no_name