Topic with some sql inthat I forgot why it exists

– [params]
– date :start_date = 2023-12-01
– date :end_date = 2023-12-31

WITH excluded_ip AS (

SELECT 
    TO_CHAR(viewed_at, 'YYYY-MM'),
    ip_address,
    COUNT(ip_address)
FROM topic_views
WHERE viewed_at BETWEEN :start_date AND :end_date
GROUP BY 1, 2
HAVING COUNT(*) > 1000

)

SELECT
    TO_CHAR(tv.viewed_at, 'YYYY-MM'),
    COUNT(tv.ip_address)
FROM topic_views tv
WHERE tv.viewed_at BETWEEN :start_date AND :end_date
  AND tv.ip_address NOT IN (SELECT ip_address FROM excluded_ip)
GROUP BY 1

WITH excluded_ip AS (

SELECT 
    TO_CHAR(viewed_at, 'YYYY-MM'),
    ip_address
FROM topic_views
WHERE viewed_at BETWEEN :start_date AND :end_date
GROUP BY 1, 2
HAVING COUNT(*) < 1000

)

SELECT
    TO_CHAR(tv.viewed_at, 'YYYY-MM') AS month,
    COUNT(*)
FROM topic_views tv
WHERE tv.viewed_at BETWEEN :start_date AND :end_date
  AND user_id ISNULL
  AND tv.ip_address IN (SELECT ip_address FROM excluded_ip)
GROUP BY month