Skip to content

Commit 2d9476d

Browse files
authored
Merge pull request #739 from cosmik-network/development
fix collection breakdown query
2 parents e7e67e2 + 2f24654 commit 2d9476d

1 file changed

Lines changed: 34 additions & 13 deletions

File tree

src/modules/user/infrastructure/repositories/DrizzleUserStatsRepository.ts

Lines changed: 34 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -437,30 +437,51 @@ export class DrizzleUserStatsRepository implements IUserStatsRepository {
437437

438438
// Optimized query for collections: use incremental aggregation with window functions
439439
const collectionsQuery = sql`
440-
WITH period_collection_counts AS (
440+
WITH all_collections AS (
441441
SELECT
442-
date_trunc(${interval}, created_at) AS period,
443442
access_type,
444-
COUNT(*)::int AS period_count
443+
created_at
445444
FROM ${collections}
446445
WHERE created_at IS NOT NULL
446+
),
447+
all_periods AS (
448+
SELECT DISTINCT date_trunc(${interval}, created_at) AS period
449+
FROM all_collections
450+
),
451+
all_access_types AS (
452+
SELECT DISTINCT access_type
453+
FROM all_collections
454+
),
455+
period_type_grid AS (
456+
SELECT p.period, t.access_type
457+
FROM all_periods p
458+
CROSS JOIN all_access_types t
459+
),
460+
period_counts AS (
461+
SELECT
462+
date_trunc(${interval}, created_at) AS period,
463+
access_type,
464+
COUNT(*)::int AS period_count
465+
FROM all_collections
447466
GROUP BY 1, 2
448467
),
468+
cumulative_counts AS (
469+
SELECT
470+
ptg.period,
471+
ptg.access_type,
472+
SUM(COALESCE(pc.period_count, 0)) OVER (
473+
PARTITION BY ptg.access_type
474+
ORDER BY ptg.period
475+
) AS cumulative_count
476+
FROM period_type_grid ptg
477+
LEFT JOIN period_counts pc ON ptg.period = pc.period AND ptg.access_type = pc.access_type
478+
),
449479
collection_aggregated AS (
450480
SELECT
451481
period::text AS date,
452482
jsonb_object_agg(access_type, cumulative_count) AS by_access_type,
453483
SUM(cumulative_count)::int AS total
454-
FROM (
455-
SELECT
456-
period,
457-
access_type,
458-
SUM(period_count) OVER (
459-
PARTITION BY access_type
460-
ORDER BY period
461-
) AS cumulative_count
462-
FROM period_collection_counts
463-
) cumulative_data
484+
FROM cumulative_counts
464485
GROUP BY period
465486
ORDER BY period DESC
466487
LIMIT ${limit}

0 commit comments

Comments
 (0)