聚合函数在指定子查询时,Sum不起作用

时间:2017-05-03 13:12:10

标签: sql-server tsql

这是我的疑问:

SELECT 
    Sum(IsNull(CircuitCourtFeeCap, 0) + IsNull(CircuitCourtCourtTime, 0) + IsNull(CircuitCourtWaiverFee, 0) + IsNull(CircuitCourtExpenseFee, 0)) AS TotalApproved,
    Sum(IsNull(e.FeeAmountCap, 0)) AS TotalFeeCap,
    Sum(IsNull((
                SELECT Claimed
                FROM [dbo].[CourtTimes] ct
                WHERE ct.DocumentNameID = dn.DocumentNameID
                ), 0)) AS TotalCourtTime
FROM DocumentNames dn
LEFT JOIN Expenses e ON dn.DocumentNameID = e.DocumentNameID

超级简单。除了这条线之外的所有Sum都不起作用:

Sum(IsNull((Select Claimed From [dbo].[CourtTimes] ct Where ct.DocumentNameID = dn.DocumentNameID), 0)) As TotalCourtTime

我收到此错误:Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

有任何想法如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

就像错误所说的那样,你不能在子查询中执行聚合函数(sum())。相反,将其他表加入FROM子句:

SELECT 
    Sum(IsNull(CircuitCourtFeeCap, 0) + IsNull(CircuitCourtCourtTime, 0) + IsNull(CircuitCourtWaiverFee, 0) + IsNull(CircuitCourtExpenseFee, 0)) AS TotalApproved,
    Sum(IsNull(e.FeeAmountCap, 0)) AS TotalFeeCap,
    Sum(IsNull(ct.CourtTime, 0)) AS TotalCourtTime
FROM DocumentNames dn
    LEFT OUTER JOIN (SELECT DocumentNameID, sum(claimed) as CourtTime FROM [dbo].[CourtTimes] GROUP BY DocumentNameID) ct
        ON ct.DocumentNameID = dn.DocumentNameID
    LEFT OUTER JOIN Expenses e 
        ON dn.DocumentNameID = e.DocumentNameID;

更新了此答案,将[CourtTimes]表连接移动到子查询中,以便在加入之前可以在DocumentNameID级别预先聚合。