DarkCode999
DarkCode999

Reputation: 182

How to get list day of month data per month in postgresql

i use psql v.10.5

and i have a structure table like this :

|     date      | total |
-------------------------
|  01-01-2018   |   50  |
|  05-01-2018   |   90  |
|  30-01-2018   |   20  |

how to get recap data by month, but the data showed straight 30 days, i want the data showed like this :

|     date      | total |
-------------------------
|  01-01-2018   |   50  |
|  02-01-2018   |   0   |
|  03-01-2018   |   0   |
|  04-01-2018   |   0   |
|  05-01-2018   |   90  |
.....
|  29-01-2018   |   0   |
|  30-01-2018   |   20  |

i've tried this query :

SELECT * FROM date
WHERE EXTRACT(month FROM "date") = 1  // dynamically
AND EXTRACT(year FROM "date") = 2018  // dynamically

but the result is not what i expected. also the params of month and date i create dynamically.

any help will be appreciated

Upvotes: 3

Views: 3148

Answers (1)

klin
klin

Reputation: 121604

Use the function generate_series(start, stop, step interval), e.g.:

select d::date, coalesce(total, 0) as total
from generate_series('2018-01-01', '2018-01-31', '1 day'::interval) d
left join my_table t on d::date = t.date

Working example in rextester.

Upvotes: 5

Related Questions