This ClickHouse SQL query demonstrates how to map each timestamp (ts) to its corresponding total increase value from an array. The initial query retrieves a series of timestamps and their associated total increase values as an array. However, the goal is to align each timestamp with its corresponding total increase value within the array.

To achieve this mapping, the query first retrieves the timestamps (ts) and the total increase array. It then uses the arrayEnumerate function to generate an index (i) for each timestamp. This index is crucial for correlating timestamps with the correct elements in the total increase array.

The if statement checks if the index (i) is greater than or equal to 31. If true, it calculates the total increase for the past 30 days using arraySlice and arraySum. Otherwise, it calculates the total increase from the beginning of the data up to the current timestamp.

The final step involves extracting the corresponding total increase value from the array. This is achieved by using the index (i) to access the appropriate element in the total_increase array using total_increase[i]. The query then sorts the results by timestamp for clarity.

SELECT ts, 
    total_increase[i] as total_increase_num 
FROM (
    SELECT ts, 
        total_increase,
        if(i >= 31, arraySum(arraySlice(total_increase, i-30, 31)), arraySum(arraySlice(total_increase, 1, i))) as total_increase_num
    FROM (
        SELECT groupArray(Ds) as t,
            groupArray(app_count) as total_increase
        from (
            SELECT min_Ds as Ds,
                count(distinct AppIdentifier) as app_count
            FROM (
                select AppIdentifier,
                    min(Ds) as min_Ds
                from log_iMonkey_iOS_overview
                GROUP BY AppIdentifier
            )
            GROUP BY min_Ds
            order by min_Ds
        ) 
    ) ARRAY
    JOIN t as ts,
    arrayEnumerate(t) as i where ts >= toDate('2023-10-26')
)
ORDER BY ts

This query provides a practical approach for mapping values from arrays to corresponding timestamps in ClickHouse, demonstrating the power and flexibility of array functions within the database.

ClickHouse SQL: Map Total Increase to Timestamps in Array

原文地址: https://www.cveoy.top/t/topic/oDpS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录