2016-10-31 11 views
0

このエラーをソートするのにお手伝いできますか?私は和の合計のクエリを持っている、私は以下のエラーが表示されているクエリを実行している。
SQLのSum()())

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 

エラー

は 集計やサブクエリを含む式に集約関数を実行できません。

+7

あなたは「私が達成したいもの」に「SQL Serverは、私のクエリを実行することを拒否する」からバックステップを取る場合は、あなたが推理を説明できますこれの後ろに?集計の観点から見ると、SUMは「SUM(SUM(...(実際には意味がありません。おそらくあなたがしたいのは、SUM(...)を内部から削除するだけです大文字小文字の区別は? –

+2

レコードをグループ化しているときは 'distinct'は必要ないことに注意してください – Bouke

+1

NOLOCKヒントを使ってクエリを捨てる前にこのトピックを少し読んでください。 //blogs.sqlsentry.com/aaronbertrand/bad-habits-nolock-everywhere/ –

答えて

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