2017-02-28 59 views
0

你们可以帮我一下吗?我已经写了一个查询来获取DocumentNoWhscode和每个文档的NetAmmount像图所示:
总和在sql server中

SELECT t1.whscode, 
CASE WHEN t0.[DiscPrcnt]>0 then ((sum(t1.LineTotal) -isnull(t0.dpmamnt,0))- ((sum(t1.LineTotal)-isnull(t0.dpmamnt,0)) * t0.[DiscPrcnt]/100)) +t0.VatSum 
ELSE ((sum(t1.LineTotal)-isnull(t0.dpmamnt,0))) END 
as 'NetAmount',t0.docnum 
from [dbo].[OINV] T0 (NOLOCK) INNER JOIN [dbo].[INV1] T1 (NOLOCK) ON T0. [DocEntry] = T1.[DocEntry] 
where t0.docdate between '02-09-17' and '02-10-17' and 
t1.WhsCode='kidst'and t0.CANCELED!='Y' and t1.targettype!=13 
group by T0.[CardName],t0.[taxdate],t0.[docduedate], T0.[DocStatus], t0.[doctotal]-t0.[vatsum], 
t1.whscode,t0.DocNum,t0.usersign,t0.DiscPrcnt,t0.dpmamnt,t0.vatsum 
having (sum(t1.LineTotal)-isnull(t0.dpmamnt,0))>0 


输出:

|whscode| NetAmount | docnum| 
    |KIDST | 2147.419293 |3411592| 
    |KIDST | 19.000011 |3411670| 
    |KIDST | 23.380000 |3411314| 
    |KIDST | 50.000000 |3412061| 
    |KIDST | 268.720000 |3412000| 
    |KIDST | 69.930000 |3412289| 

现在我想获得输出作为Whscode总和为NetAmount like:

|Whscode| NetAmount | 
    KIDST----2578.449 

如果我这样做sum(case结束)抛出一个错误无法对包含聚合或子查询的表达式执行聚合函数。
请任何人都可以帮助我。

+0

(从两个选择,并通过集团) –

+0

从您的查询的字段“docnum”如果我还删除其显示同样的错误。 ((sum(t1.LineTotal)-isnull(t0.dpmamnt,0)) - ((sum(t1.LineTotal)-isnull(t0(t0.dpmamnt,0)) - ((sum(t1.LineTotal)-isnull(t0.dpmamnt,0)))END) as'NetAmount' from(from gamasutra) [OINV] T0(NOLOCK)INNER JOIN [dbo]。[INV1] T1(NOLOCK)ON T0。[DocEntry] = T1。[DocEntry] where't0.docdate between '02-09-17'and '02 -10-17'and t1.WhsCode ='kidst' and t0.CANCELED!='Y'and t1.targettype!= 13 group by t1.whscode –

回答

1

请试试这个:

;with cte as (
SELECT t1.whscode, 
CASE WHEN t0.[DiscPrcnt]>0 then ((sum(t1.LineTotal) -isnull(t0.dpmamnt,0))- ((sum(t1.LineTotal)-isnull(t0.dpmamnt,0)) * t0.[DiscPrcnt]/100)) +t0.VatSum 
ELSE ((sum(t1.LineTotal)-isnull(t0.dpmamnt,0))) END 
as 'NetAmount',t0.docnum 
from [dbo].[OINV] T0 (NOLOCK) INNER JOIN [dbo].[INV1] T1 (NOLOCK) ON T0. [DocEntry] = T1.[DocEntry] 
where t0.docdate between '02-09-17' and '02-10-17' and 
t1.WhsCode='kidst'and t0.CANCELED!='Y' and t1.targettype!=13 
group by T0.[CardName],t0.[taxdate],t0.[docduedate], T0.[DocStatus], t0.[doctotal]-t0.[vatsum], 
t1.whscode,t0.DocNum,t0.usersign,t0.DiscPrcnt,t0.dpmamnt,t0.vatsum 
having (sum(t1.LineTotal)-isnull(t0.dpmamnt,0))>0 
) 
select whscode,sum(Netamount) as NetAmount 
from cte 
group by whscode 
+0

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

+0

你可以尝试插入'Temptable'吗?然后得到'NetAmount'的总和 –

+0

是的,我已经尝试过,仍然没有运气。同样的错误显示 –