0

我正在编写一个查询,我需要根据 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;

有没有其他方法可以做到这一点?

4

3 回答 3

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
于 2013-06-25T05:52:00.260 回答
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;
于 2013-06-25T05:53:00.037 回答
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
于 2013-06-25T05:53:22.733 回答