I am querying a postgresql 9.4 database and I want to perform calculations using columns inside the same query.
The result I am trying to obtain is a partial value based on the number of days passed out of a total_days amount. E.g.
- start_date: 01/01/2016,
- duration_in_months: 2,
- total_days: 60,
- value_x: 120.
If I launch the query today, 05/01/2016, I want to obtain:
partial_result = value_x * passed_days / total_days
120 * 5 / 60
In my dataset, I have over 100k records and I need to get this partial value grouped by month (adding the partials month by month).
=========================================================================
In MySQL I am able to do calculation as follows:
SELECT
start_date,
duration_in_months,
@end_date:= DATE_ADD(start_date, INTERVAL duration_in_months MONTH) as end_date,
@total_days:= DATEDIFF(@end_date, start_date),
@passed_days:= DATEDIFF(CURDATE(), start_date),
value_x,
(value_x * @passed_days / @total_days) as partial_result
FROM table;
Following the instructions found in this question previously asked, I am currently using in PostgreSQL a query like:
SELECT
start_date,
duration_in_months,
end_date,
total_days,
value_x,
(value_x * passed_days / total_days) as partial_result
FROM (SELECT *,
(start_date + (duration_in_months || ' month')::INTERVAL) as end_date,
EXTRACT(DAY FROM (start_date + (duration_in_months || ' month')::INTERVAL) - start_date) as total_days,
EXTRACT(DAY FROM current_date - start_date) as passed_days
FROM table) as table1;
I would need your help in order to:
- use calculated variables in PostgreSQL like in MySQL using formulas in the query or find another way to make the query more readable
- group the partials results by months
insert a where clause to ensure that
passed_days >= 0 and passed_days <= total_days
Thank you very much in advance and feel free to ask for more details.