SQL中的Sum(Sum())

时间:2016-10-31 10:55:42

标签: sql-server tsql

可以请任何人帮我解决这个错误。我有一个总和的查询,执行查询时我有一个错误如下所示。

select distinct
    t1.whscode,
    'Invoice',
    count(distinct t1.DocEntry),
    sum(
        case when t0.DiscPrcnt>0 and t0.DpmAmnt>0 then
            (sum(t1.LineTotal)-t0.DiscPrcnt)-t0.DpmAmnt
        else 
            (sum(t1.LineTotal)-t0.DpmAmnt)
        end
    )
from 
    oinv t0 (NOLOCK) 
    inner join inv1 t1 (NOLOCK)
        on t0.docentry=t1.docentry 
where 
    t0.DocDate between '10-25-16' and '10-25-16'
    and t1.whscode='tamst' 
group by
    t1.whscode

错误

  

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

1 个答案:

答案 0 :(得分:0)

您可以使用OVER,如下所示:

SELECT
    A.whscode,
    'Invoice',
    COUNT(distinct A.DocEntry),
    SUM(case when A.DiscPrcnt > 0 and A.DpmAmnt > 0 then (A.LineTotal - A.DiscPrcnt)-A.DpmAmnt else (A.LineTotal-A.DpmAmnt) end)
FROM
(
    SELECT 
        t1.whscode,
        t1.DocEntry,
        t0.DiscPrcnt,
        t0.DpmAmnt,
        sum(t1.LineTotal) OVER (PARTITION BY t1.whscode) LineTotal
    from oinv t0 (NOLOCK) inner join inv1 t1 (NOLOCK) on t0.docentry=t1.docentry 
    where t0.DocDate between '10-25-16' and '10-25-16' and t1.whscode='tamst' 
) A
GROUP BY
    A.whscode