SQL 查询优化:如何统计特定平台数据并计算平均值
您可以使用 HAVING 子句来筛选出 PlatformType = 5 的数据,并且使用 COUNT 函数来获取对应的数据数量。然后在 SELECT 子句中使用 CASE 语句来判断当 PlatformType = 5 时,index_avgdevicetime_0 的值应该是 sum(AvgDeviceTime) 除以 PlatformType = 5 对应的数据数量。以下是修改后的 SQL 查询语句:
SELECT
toStartOfDay(toDateTime(Ds)) AS datetime_day_Ds,
PlatformType AS PlatformType,
sum(AvgDeviceTime) AS index_avgdevicetime_0,
CASE WHEN PlatformType = 5 THEN sum(AvgDeviceTime) / COUNT(*) END AS index_avgdevicetime_5
FROM log_iMonkey_Wechat_overview
WHERE
Debug = 0 AND
PlatformType != 0 AND
Ds >= toDateTime('#day_device_ave_wechat_time.start#') AND
Ds <= toDateTime('#day_device_ave_wechat_time.end#')
GROUP BY
datetime_day_Ds,
PlatformType
HAVING
PlatformType = 5 OR PlatformType != 5
ORDER BY
datetime_day_Ds DESC,
PlatformType DESC
LIMIT 5000;
这样,当 PlatformType = 5 时,会输出对应的数据数量,并且 index_avgdevicetime_0 的值是 sum(AvgDeviceTime) 除以 PlatformType = 5 对应的数据数量。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/pG4J 著作权归作者所有。请勿转载和采集!