I have a simple table that contains trips over different dates.
| trip_id | start_date | end_date |
|---|---|---|
| 160320 | 2017-12-31 20:40:25 UTC | 2017-12-31 20:45:25 UTC |
| 160321 | 2018-01-12 21:01:51 UTC | 2018-01-12 22:01:51 UTC |
I simply want to create a SQL query that shows these fields.
- year
- month
- trips_this_month,
- trips_previous_month
- difference_from_previous_month (count_this_month - count_previous_month)
- is_increased (is a boolean column that is true if we saw an increase, false otherwise) Update: I could wrap up my head and write a simple query to obtain them, but I still feel I can optimize this query. Any help will be appreciated.
SELECT
year,
month,
trips_this_month,
trips_previous_month,
case when difference_from_previous_month < 0 then false else true end as is_increased
FROM
(SELECT
year,
month,
number_of_trips AS trips_this_month,
LAG(number_of_trips,1,0) over (order by year,month) AS trips_previous_month,
number_of_trips - LAG(number_of_trips,1,0) OVER(order by year,month) AS difference_from_previous_month,
FROM(
SELECT EXTRACT(Month FROM start_date) AS month,
EXTRACT(Year FROM start_date) AS year,
COUNT(*) as number_of_trips
FROM a_table
group by month ,year
)
order by year, month
limit 100
)
But I could not help myself to do more. I appreciate with further helps to complete it.