created_at
attributeSELECT to_char(created_at, 'Month') as mon,
extract(year from created_at) as yyyy,
COUNT(*) as "Total"
FROM table_name
WHERE extract(year from created_at) = extract(year from now())
GROUP BY 1,2;
to_char()
converts the created_at
attribute into the defined format of the month, use 'Mon'
fior
for the shorter month name version.extract()
is used to retrieve subfields from an attribute. For example: year, month, etc. from the specified
attribute.COUNT(*)
to retrieve the count of all records within that month and yearWHERE
clause is used to specify records from the current year!group by
clause is used to organize the results based on all the columns specified in the
select
clause. 1, 2;
is a shorthand notation for the column 1 and column 2 in the select statement
otherwise for better readability replace 1, 2;
with to_char()..., extract()...
the 2 columns
in the select
statement.select *,
COUNT(CASE WHEN month = 1 THEN 1 END) as january,
...,
COUNT(CASE WHEN month = 12 THEN 1 END) as december
from (
select *, EXTRACT(month from created_at) as month
from ...
join ...
where
) table_name
group by 1;