2014-06-19 168 views
0

這是我的初始查詢:如何SUM包含嵌套的select語句的case語句?

select 
CASE WHEN a.TO_WG_ID is null 
and a.CREATED_DATE_TIME = 
(select min(b.created_date_time) from ymtn.message b 
where b.thread_id = a.thread_id) THEN 1 ELSE 0 
END AS "Created" 
from ymtn.MESSAGE a 
left join YMTN.WORKGROUP b 
ON a.FROM_WG_ID=b.WORKGROUP_ID 
where b.WORKGROUP_ID='1STOP_PROCESS' 

它給了我和一幫1' 和0的一列。我想要的只是總和......只是一個數字,例如1691.如果我把一個SUM放在case語句前,我得到這個錯誤: Msg 130,Level 15,State 1,Line 5 無法對包含聚集或子查詢的表達式執行聚合函數。那我該怎麼做呢?我已與此查詢工作:

select count(CREATED_DATE_TIME) as 'Created' 
from ymtn.MESSAGE a 
LEFT JOIN YMTN.WORKGROUP b 
ON a.FROM_WG_ID=b.WORKGROUP_ID 
where CREATED_DATE_TIME=(SELECT MIN(b.CREATED_DATE_TIME) FROM YMTN.MESSAGE b WHERE 
b.THREAD_ID = a.THREAD_ID) 
and a.TO_WG_ID is null 
and b.WORKGROUP_ID='1STOP_PROCESS' 

但是我希望它在case語句工作,而不必移動嵌套選擇到WHERE子句。

回答

1

你可以把整個事情放入一個子查詢中,然後求和?

select sum(Created) 
from (
    select 
    CASE WHEN a.TO_WG_ID is null 
    and a.CREATED_DATE_TIME = 
    (select min(b.created_date_time) from ymtn.message b 
    where b.thread_id = a.thread_id) THEN 1 ELSE 0 
    END AS "Created" 
    from ymtn.MESSAGE a 
    left join YMTN.WORKGROUP b 
    ON a.FROM_WG_ID=b.WORKGROUP_ID 
    where b.WORKGROUP_ID='1STOP_PROCESS' 
) a 
+0

這是有效的。感謝您的解決方案。 –