无法对包含子查询的表达式执行聚合函数

Cannot perform an aggregate function on an expression containing subquery

我试图在 SELECT 语句中包含子查询,但出现错误:

"Cannot perform an aggregate function on an expression containing an aggregate or a subquery."

DECLARE @ShN money=STRLOG.dbo.fn_VarValue('ShN') 
DECLARE @ShNs money=STRLOG.dbo.fn_VarValue('ShNs') 
DECLARE @ShNN money=STRLOG.dbo.fn_VarValue('ShN') +STRLOG.dbo.fn_VarValue('ShNs') 
DECLARE @ShD money=STRLOG.dbo.fn_VarValue('ShD') 

    SELECT sum(
        CASE 
            WHEN GR2='33' 
            THEN @ShN

            WHEN GR2='3' 
            THEN 
                CASE 
                -- find if next day is day off          
                WHEN EXISTS (SELECT * FROM tbl_Holidays WHERE [HolidayDate]=DATEADD("DAY",1,'2014.11.30'))
                THEN @ShNs  
                ELSE @ShNN 
                END
            ELSE @ShD
        END
        )/60, 
        tbl_Tabel.EmplCodeID
        FROM tbl_TabelWHrs INNER JOIN tbl_Tabel ON tbl_TabelWHrs.TabWHrsID = tbl_Tabel.TabWHrsID
        WHERE (tbl_TabelWHrs.TabMon='2014.12' AND tbl_Tabel.EmplCodeID='7040023' AND GR2 is not null)
        GROUP BY tbl_Tabel.EmplCodeID;

看似简单,但我对子查询还很陌生。能请谁给我指路吗。

在大多数情况下,使用内联查询是一种不好的做法。没有不能改成join, left join, subquery的例子。而且在 90% 的情况下,内联查询的效果会更差。

尝试做类似的事情:

DECLARE @ShN money=STRLOG.dbo.fn_VarValue('ShN') 
DECLARE @ShNs money=STRLOG.dbo.fn_VarValue('ShNs') 
DECLARE @ShNN money=STRLOG.dbo.fn_VarValue('ShN') +STRLOG.dbo.fn_VarValue('ShNs') 
DECLARE @ShD money=STRLOG.dbo.fn_VarValue('ShD') 

    SELECT sum(
        CASE 
            WHEN GR2='33' 
            THEN @ShN

            WHEN GR2='3' 
            THEN 
                CASE 
                -- find if next day is day off          
                WHEN th.SomeKey IS NOT NULL
                THEN @ShNs  
                ELSE @ShNN 
                END
            ELSE @ShD
        END
        )/60, 
        tbl_Tabel.EmplCodeID
        FROM tbl_TabelWHrs INNER JOIN tbl_Tabel ON tbl_TabelWHrs.TabWHrsID = tbl_Tabel.TabWHrsID
        LEFT JOIN tbl_Holidays th
          ON [HolidayDate]=DATEADD("DAY",1,'2014.11.30')
        WHERE (tbl_TabelWHrs.TabMon='2014.12' AND tbl_Tabel.EmplCodeID='7040023' AND GR2 is not null)

        GROUP BY tbl_Tabel.EmplCodeID;