# Looking to build a custom report - time between last two responses on a topic

**URL:** <https://meta.discourse.org/t/looking-to-build-a-custom-report-time-between-last-two-responses-on-a-topic/299431>\
**Category:** Data & reporting\
**Tags:** sql-query\
**Created:** [March 15, 2024, 12:10am UTC](https://meta.discourse.org/t/looking-to-build-a-custom-report-time-between-last-two-responses-on-a-topic/299431 "2024-03-15T00:10:47Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![hendersj](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/hendersj/32/507887_2.png) [@hendersj](https://meta.discourse.org/u/hendersj)\
**Post date:** [March 15, 2024, 9:05pm UTC](https://meta.discourse.org/t/looking-to-build-a-custom-report-time-between-last-two-responses-on-a-topic/299431/2 "2024-03-15T21:05:47Z")

</div>

For anyone interested, here’s what seems to work:

```plaintext
-- [params]
-- null date :start_date
-- null date :end_date
-- null int_list :category_ids

WITH RankedPosts AS (
    SELECT 
        p.topic_id,
        p.created_at,
        ROW_NUMBER() OVER (PARTITION BY p.topic_id ORDER BY p.post_number DESC) AS rank
    FROM 
        posts p
    WHERE 
        p.created_at BETWEEN :start_date AND :end_date
        AND EXISTS (
            SELECT 1
            FROM topics t
            WHERE t.id = p.topic_id
            AND t.category_id IN (:category_ids)
        )
),
FilteredPosts AS (
    SELECT 
        topic_id,
        created_at,
        rank
    FROM 
        RankedPosts
    WHERE 
        rank <= 2
),
PostDifferences AS (
    SELECT 
        topic_id,
        EXTRACT(days FROM (MAX(created_at) FILTER (WHERE rank = 1) - MAX(created_at) FILTER (WHERE rank = 2)))::numeric(9,2) AS days_difference
    FROM 
        FilteredPosts
    GROUP BY 
        topic_id
)
SELECT 
    t.category_id,
    AVG(pd.days_difference) AS avg_days_difference,
    PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY pd.days_difference) AS median_days_difference
FROM 
    topics t
JOIN 
    PostDifferences pd ON t.id = pd.topic_id
GROUP BY 
    t.category_id
ORDER BY
    avg_days_difference DESC

```

This should give the mean and median of the times between the creation timestamps. The update timestamps seemed problematic (I got some negative values for some reason when just doing averages).

I had some AI assistance with creating the query, so it’s possible that there are mistakes - and I’m happy if anyone has suggestions about how to improve it (or correct any errors). The results that I got seemed reasonable based on checks made on smaller groups, as well as changes resulting from increasing the date range resulting in trends that aligned with expectations I had from using a larger data sample.

---

_[View the full topic](https://meta.discourse.org/t/looking-to-build-a-custom-report-time-between-last-two-responses-on-a-topic/299431)._
