如何与案例功能汇总

时间:2016-12-09 15:09:41

标签: sql function case aggregate-functions

我有一些可行的代码,但我需要计算一些dta,似乎无法使其工作。

请参阅下面的代码,并且带有注释的on不起作用。

{{1}}

1 个答案:

答案 0 :(得分:0)

试试这个:

select 
    siteid,
    linenum,
    worktype,
    sum(case when status = 'appr'   then 1 else null end) as [approved],
    sum(case when status = 'review' then 1 else null end) as [review],
    sum(case when status = 'wmatl'  then 1 else null end) as [waitmatl],
    sum(case when status = 'comp'   then 1 else null end) as [complete],
    sum(case when status = 'incomp' then 1 else null end) as [incomplete],
    sum(case when status = 'closed' then 1 else null end) as [closed],
    sum(case when status not in ('appr','wmatl') then 1 else null end) as [all_completed],
    count (*) as allrecords,
    sum(case when status not in ('appr','wmatl') then 1 else null end)  / count (*) as completion_ratio
  from workorder
  where (siteid in ('p202','p203','p201')) 
    and (worktype in   ('mpm','ppm','tspm')) 
    and (istask ='0') 
    and (historyflag ='0') 
    and (woclass = 'workorder') 
    --and (status not in ('comp','closed','review','incomp'))
    and (assetnum is not null)
    and (maintby not in ('ms','ed')) 
    and targcompdate < dateadd(mm,datediff(mm,0,getdate())-0,0)
  group by siteid, linenum, worktype
  order by siteid, linenum, worktype