你能帮帮我吗?我写了一个查询来获取每个文档的DocumentNo
,Whscode
和NetAmmount
,如下所示:
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
的总和如下:
|Whscode| NetAmount |
KIDST----2578.449
如果我执行sum
(情况结束)抛出错误无法对包含聚合或子查询的表达式执行聚合函数。
请允许任何人帮助我。
答案 0 :(得分: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