# New topics per category (by month)

**URL:** https://meta.discourse.org/t/new-topics-per-category-by-month/275047
**Category:** Data & reporting
**Tags:** sql-query
**Created:** [12 februari 2018 om 10:37 UTC](https://meta.discourse.org/t/new-topics-per-category-by-month/275047 "2018-02-12T10:37:00Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![simon](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/simon/32/339122_2.png) [@simon](https://meta.discourse.org/u/simon)
#### Post date: [12 februari 2018 om 10:37 UTC](https://meta.discourse.org/t/new-topics-per-category-by-month/275047/1 "2018-02-12T10:37:00Z")

</div>

### New topics per category (by month)

Returns the number of new topics created in each category for a given month, ordered by topic\_count. The query accepts a ‘months ago’ parameter, defaults to 0 to give the results for the current month.

```sql
-- [params]
-- int :months_ago = 1

WITH query_period as (
    SELECT
        date_trunc('month', CURRENT_DATE) - INTERVAL ':months_ago months' as period_start,
        date_trunc('month', CURRENT_DATE) - INTERVAL ':months_ago months' + INTERVAL '1 month' - INTERVAL '1 second' as period_end
)

SELECT
    t.category_id,
    count(1) as topic_count
FROM topics t
RIGHT JOIN query_period qp
    ON t.created_at >= qp.period_start
        AND t.created_at <= qp.period_end
WHERE t.user_id > 0
    AND t.category_id IS NOT NULL
GROUP BY t.category_id
ORDER BY topic_count DESC

```
