使用avg,分组依据和一起使用大小写-db2

时间:2018-12-03 20:14:28

标签: group-by db2 case average

我有以下工作代码可返回位置,州和月份年份的每种组合。

select *
from openquery (jw,'
select distinct a.location, a.state, a.monthyear
from (
    select clm.location, clm.state,
    case 
        when EFDT>=''2017-09-01'' and EFDT<=''2017-09-30'' Then ''Sept 2017''
        when EFDT>=''2017-10-01'' and EFDT<=''2017-10-31'' Then ''Oct 2017''
        when EFDT>=''2017-11-01'' and EFDT<=''2017-11-30'' Then ''Nov 2017''
        when EFDT>=''2017-12-01'' and EFDT<=''2017-12-31'' Then ''Dec 2017''
        when EFDT>=''2018-01-01'' and EFDT<=''2018-01-31'' Then ''Jan 2018''
        when EFDT>=''2018-02-01'' and EFDT<=''2018-02-28'' Then ''Feb 2018''
        when EFDT>=''2018-03-01'' and EFDT<=''2018-03-31'' Then ''March 2018''
        when EFDT>=''2018-04-01'' and EFDT<=''2018-04-30'' Then ''April 2018''
        when EFDT>=''2018-05-01'' and EFDT<=''2018-05-31'' Then ''May 2018''
        when EFDT>=''2018-06-01'' and EFDT<=''2018-06-30'' Then ''June 2018''
        when EFDT>=''2018-07-01'' and EFDT<=''2018-07-31'' Then ''July 2018''
        when EFDT>=''2018-08-01'' and EFDT<=''2018-08-31'' Then ''Aug 2018''
        when EFDT>=''2018-09-01'' and EFDT<=''2018-09-30'' Then ''Sept 2018''
        when EFDT>=''2018-10-01'' and EFDT<=''2018-10-31'' Then ''Oct 2018''
        when EFDT>=''2018-11-01'' and EFDT<=''2018-11-30'' Then ''Nov 2018''
        when EFDT>=''2018-12-01'' and EFDT<=''2018-12-31'' Then ''Dec 2018''
        ELSE ''null''
    END as monthyear
    from alias.table1 clm
    where ....
) a
group by location, state, monthyear
order by monthyear
with ur')

现在我正在努力添加AVG以获得每种组合的平均时间,代码如下:

avg(days(LSDT)-days(EFDT))

我该如何将Avg与group by和case结合使用?任何建议表示赞赏。我需要显示渠道,州和月年的每种组合在这两个日期之间的平均时间

1 个答案:

答案 0 :(得分:0)

尝试一下:

select location, state, monthyear, avg(days(LSDT)-days(EFDT)) as days
from (
select clm.location, clm.state, clm.lsdt, clm.efdt
, case 
    when EFDT between date('2017-09-01') and date('2018-12-31') then to_char(EFDT, 'Mon')||' '||year(EFDT) 
    else 'null' 
  end monthyear
from alias.table1 clm
)
group by location, state, monthyear
order by monthyear;