简体   繁体   中英

Best approach to parametrized aggregates

I am gathering analytics for my app. For each metric I track, I allow it to be viewed over an interval of 7, 30 or 90 days, along with grouping by date, by weekday or by time of day.

What's the best approach to handle this?

Is it possible to avoid having perform 6 different queries 6 for each metric (1 for each interval, one for each grouping)?

Example

Median conversation response time (group by day of week) Analytic(mon, tue, wed..)

Median conversation response time (group by time of day) Analytic(1 am, 2 am, 3 am..)

New conversations (group by day of week) Analytic(mon, tue, wed..)

New conversations (group by date) Analytic(20 aug, 19 aug, 18 aug etc...)

Sorry for mixing a little posgressql whit sql-server. The @... (eg @Param) are sql-server syntax for variable I don't know postgressql syntax for it but hopefully this will still illustrate the technique.

SELECT
    date
    ,CASE
       WHEN @Param = 'date' THEN date AS
       WHEN @Param = 'dow' THEN EXTRACT(DOW FROM date)
       ....
       ELSE
    END as ParamGRoup
     ,SUM(amount) as TotalAmount
FROM
    Table
WHERE
    date BETWEEN @LowDateParam TO @HighDateParam
GROUP BY
    date
    ,CASE
       WHEN @Param = 'date' THEN date AS
       WHEN @Param = 'dow' THEN EXTRACT(DOW FROM date)
       ....
       ELSE
    END as ParamGRoup

I typed this before you got your example out so I hope it is still clear. Anyway, one way you can do it is to use a case statement and then group by the same case statement. You may have to cast the THEN/Else portions of case statement as a VARCHAR or something to ensure consistent datatype if it is ever possible for it to be grouped by multiple levels but it should get you there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM