我正在编写一个查询,根据avg()聚合函数的条件,我需要select stmt的结果,
但是在mysql中它给出了错误错误代码:1111, 组功能的使用无效
select
if( avg(FLD_TKTS) > 1 and avg(FLD_TKTS) <= 2 , '1-2' , 0) as fld_avg_1_2,
if( avg(FLD_TKTS) > 3 and avg(FLD_TKTS) <= 4 , '3-4' , 0) as fld_avg_3_4
from tbl
group by region;
还有其他方法吗?
答案 0 :(得分:2)
查询:
select
CASE WHEN avg(FLD_TKTS) > 1 and avg(FLD_TKTS) <= 2 THEN '1-2'
ELSE '0' END as fld_avg_1_2,
CASE WHEN avg(FLD_TKTS) > 3 and avg(FLD_TKTS) <= 4 THEN '3-4'
ELSE '0' END as fld_avg_3_4
from tbl
group by region
答案 1 :(得分:1)
select
region,
if(fld_avg > 1 and fld_avg <= 2, '1-2', 0) as fld_avg_1_2,
if(fld_avg > 3 and fld_avg <= 4, '3-4', 0) as fld_avg_3_4
from
(
select
region,
avg(FLD_TKTS) fld_avg
from
tbl
group by
region
) a;
答案 2 :(得分:0)
我认为子查询是一个很好的解决方案:
SELECT
IF( avg_fld_tkts > 1 and avg_fld_tkts <= 2 , '1-2' , 0) as fld_avg_1_2,
IF( avg_fld_tkts > 3 and avg_fld_tkts <= 4 , '3-4' , 0) as fld_avg_3_4
(
SELECT avg(FLD_TKTS) AS avg_fld_tkts
from tbl
group by region
) t1