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

时间:2015-01-23 06:58:01

标签: sql-server subquery expression case aggregate-functions

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

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

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;

看起来很简单,但我对子查询很新。能不能请有人告诉我方向。

1 个答案:

答案 0 :(得分:1)

在大多数情况下,使用内联查询是一种不好的做法。没有示例您无法将其更改为连接,左连接,子查询。在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;