关于CASE中使用聚合函数时的一点经验

先不要管以下代码是完成什么功能
--==片段1==
select
    case when SUM(isnull(ACTVTY_DURTN,0))>=1 then 1 else SUM(isnull(ACTVTY_DURTN,0)) end as DURTN
,OWNR_EMP_ID_NK
from dbo.ECMS_Activity_DIMN AC
    
    WHERE AC.APPT_STRT_DT_TZ BETWEEN '201208' AND '201209'
    AND AC.actvty_main_type = 'Coaching'    
    AND AC.CURR_RECRD_FLG='Y'
            --===========================
    --错误:Column 'dbo.ECMS_Activity_DIMN.OWNR_EMP_ID_NK' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
   
--==片段2==
    --无错
    select
    distinct
    CASE WHEN CAST(APPT_STRT_DT_TZ AS TIME(6))<='12:00:00' THEN 'Call_AM' ELSE 'Call_PM' end Call_Period,
    CAST(APPT_STRT_DT_TZ as date) as CallDate,
    OWNR_EMP_ID_NK
from dbo.ECMS_Activity_DIMN AC
    
    WHERE AC.APPT_STRT_DT_TZ BETWEEN '201208' AND '201209'
    AND AC.ACTVTY_MAIN_TYPE='Professional Call' AND AC.ACTVTY_SUBTYPE_CALL in(N'完整拜访',N'简短拜访')
    AND AC.CURR_RECRD_FLG='Y' and AC.ACTVTY_STS_CD='Submit'
 
片段1为什么会报错,百思不得其解。检查语法正常,一执行就提示错误。按提示加 GROUP BY OWNR_EMP_ID_NK 后,确实无错了,为什么呢
问了一朋友后得到如下答案:
 
你case里面用聚合函数,需要制定group by,要么就都用聚合函数
不能有的用聚合,有的不用聚合,还没有group by
一般也不会吧聚合函数放在case中
确实是我在片段1的CASE中使用了SUM聚合函数而片段2中没有。
按照上面这段话,我故意修改片段1 中OWNR_EMP_ID_NK为MAX(OWNR_EMP_ID_NK) ,执行也没错了
 
 
朋友看了我的片段1说很不理想,然后写出如下片段
--3优化的写法
    DECLARE @DurtnSum DECIMAL;
SELECT @DurtnSum = SUM(COALESCE(ACTVTY_DURTN,0)) FROM dbo.ECMS_Activity_DIMN AC
WHERE AC.APPT_STRT_DT_TZ BETWEEN '201208' AND '201209'
AND AC.actvty_main_type = 'Coaching'
AND AC.CURR_RECRD_FLG = 'Y'
IF @DurtnSum > 1 OR @DurtnSum = 1
BEGIN
    SET @DurtnSum = 1
END
SELECT @DurtnSum AS DURTN ,
OWNR_EMP_ID_NK
FROM dbo.ECMS_Activity_DIMN AC
WHERE AC.APPT_STRT_DT_TZ BETWEEN '201208' AND '201209'
AND AC.actvty_main_type = 'Coaching'
AND AC.CURR_RECRD_FLG = 'Y'

最后说说这段代码是做什么的:
 
一天开一个会算0.5个单位,一天里可以开N个会,但一天最多计1个单位,返回每个人每天的单位
 
posted @ 2012-10-09 13:42  net515  阅读(3067)  评论(0编辑  收藏  举报