我有下表:
date | data_type | data_value
01-01-2023 | max | 4
02-01-2023 | min | 7
03-01-2023 | avg | 54
04-01-2023 | max | 8
05-01-2023 | min | 98
06-01-2023 | avg | 23
01-02-2023 | max | 65
02-02-2023 | min | 2
03-02-2023 | avg | 45
04-02-2023 | max | 22
05-02-2023 | min | 56
06-02-2023 | avg | 65
01-03-2023 | max | 7
02-03-2023 | min | 5
03-03-2023 | avg | 23
04-03-2023 | max | 65
05-03-2023 | min | 51
06-03-2023 | avg | 33
从下表中,我需要按当前月份分组,并从中获取其数据类型为“max”的最大值,类型为“min”的较小值,最后是类型“avg”的平均值,如下:
mounth | max | min | avg
1 | 8 | 7 | 38,5
2 | 65 | 2 | 55
3 | 65 | 5 | 28
因此我想问你哪个是性能最好的 SQL 查询来解决请求。
谢谢大家
使用条件聚合如下:
select year(date_) as 'yaer',
month(date_) as 'month',
min(case when data_type = 'min' then data_value end) as 'min',
max(case when data_type = 'max' then data_value end) as 'max',
avg(case when data_type = 'avg' then data_value end) as 'avg'
from tbl
group by year(date_), month(date_)
或者,如果您想汇总特定年份:
select month(date_) as 'month',
min(case when data_type = 'min' then data_value end) as 'min',
max(case when data_type = 'max' then data_value end) as 'max',
avg(case when data_type = 'avg' then data_value end) as 'avg'
from tbl
where year(date_) = 2023
group by month(date_)