2016-12-09 2 views
0

나는 작동하는 몇 가지 코드가 있지만 일부 dta를 계산해야하고 작동하지 않는 것처럼 보일 수 있습니다.케이스 함수로 집계하는 방법

아래의 코드를 참조하십시오. 및에 대한 주석이 함께 작동하지 않습니다.

SELECT 
    siteid, 
    linenum, 
    worktype, 
    COUNT(CASE WHEN status = 'APPR' THEN 1 ELSE NULL END) AS [Approved], 
    COUNT(CASE WHEN status = 'review' THEN 1 ELSE NULL END) AS [Review], 
    COUNT(CASE WHEN status = 'wmatl' THEN 1 ELSE NULL END) AS [WaitMatl], 
    COUNT(CASE WHEN status = 'comp' THEN 1 ELSE NULL END) AS [Complete], 
    COUNT(CASE WHEN status = 'incomp' THEN 1 ELSE NULL END) AS [InComplete], 
    COUNT(CASE WHEN status = 'closed' THEN 1 ELSE NULL END) AS [Closed], 
    COUNT(CASE WHEN status not in ('appr','wmatl') THEN 1 ELSE NULL END) AS [All_Completed], 
    Count (*) as allrecords, 
    /* The below divide by does not work */ 
    COUNT(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 
+0

은 내가 얻을 모두 1 –

+0

가 @LandonH 당신은 당신의 코드를 시도한다는 의미합니까 "내가 얻을 모두가 1 인 것을 시도"라고 했어요? 왜 당신은 코멘트가 아닌 질문으로 게시 했습니까? –

+0

Opps. 누군가 내가 사용하려고 시도했다는 의견을 보았습니다. COUNT ('appr', 'wmatl')에없는 상태 THEN 1 ELSE 0 END)/Completion_Ratio로 Count (*) –

답변

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