2016-06-22 33 views
0

の3種類の方法を数えて、私は、次のデータセットを取得するクエリを書くための正しい方法を見つけようとしている:SQL ServerのSUMは、同じ出力

CustName  CityID  TransactionCount Complete InProc 
Hammertown  10001  200     50   150 
SportsAuth  10002  10     1   9 

「完了」小さく、 TransactionCountの組別の列示されていない(フォーマット)に等しい場合、それはTransactionCountの和であるべきである。

having [format]=23 
or [format]=25 
or [format]=38 
or [format]>=400 and [format]<=499 
or [format]>=800 and [format]<=899 

「インプロセス」はその後TransactionCount値の残りの部分であるべきです。これまでのところ私は、次のを作ってみた:

SELECT c.CustName, 
t.[City], 
sum (t.[TransactionCount]) as InProc 
FROM [log].[dbo].[TransactionSummary] t 
JOIN [log].[dbo].[Customer] c 
on t.CustNo = c.CustNo 
and t.City = c.City 
and t.subno = c.subno 
where t.transactiondate between '6/1/16' and '6/22/16' 
group by c.CustName,t.City,t.TransactionCount,[format] 
having [format]=23 
or [format]=25 
or [format]=38 
or [format]>=400 and [format]<=499 
or [format]>=800 and [format]<=899 

これは、現在、以下のデータを出力:「

CustName  CityID  InProc 
Hammertown  10001  147 
Hammertown  10001  1 
Hammertown  10001  1 
Hammertown  10001  1 
SportsAuth  10002  4 
SportsAuth  10002  4 
SportsAuth  10002  1 

は、だから私は、各顧客のために戻って1件の結果を得ていない午前だけではなく、私はドンこのクエリを壊すことなく他の2つの列を追加する方法を知っています。私が得ることができるどんな助けでも大いに感謝されるでしょう。

+1

こととなります? http://stackoverflow.com/questions/37971573/sql-adding-column-a-depend-on-value-in-column-b –

+0

サンプルデータなしの出力は、あなたの問題を理解するのに役立ちません –

答えて

0
SELECT sq.*, sq.TransactionCountTotal - sq.CompleteTotal as InProcTotal from 
(
    select 
    c.CustName, 
    t.[City], 
    sum (t.TransactionCount) as TransactionCountTotal 
    sum (
     case 
      when (
       [format] in (23,25,38) 
       or [format] between 400 and 499 
       or format between 800 and 899 
       ) 
     then t.TransactionCount 
     else 0 
     end 
    ) as CompleteTotal 
    FROM [log].[dbo].[TransactionSummary] t 
    INNER JOIN [log].[dbo].[Customer] c 
     on t.CustNo = c.CustNo 
     and t.City = c.City 
     and t.subno = c.subno 
    where t.transactiondate between '6/1/16' and '6/22/16' 
    group by c.CustName,t.City 
) sq 
+0

ウィザード。ありがとうございます、これはまさに私が達成したいと思っていたものです。 – jwabsolution1

+0

ありがとう! '(条件(条件)(値)else else end)'は、グループ内の何かをバケット化する必要があるこれらのタイプのクエリにとって非常に便利です。 – Eric

0

CustNameとCityIDで2つのサブセットを取得できるとします(例はあまり明確ではありません)。単純な結合はそれらを一緒に引き出すことができます。以下の例では、別名Aは、主要約とエイリアスBは、ので、あなたの他の質問で発生するもので、プロセス

Select A.CustName 
     ,A.CityID 
     ,A.TransactionCount 
     ,Complete = A.TransactionCount - isnull(B.InProc,0) 
     .InProc = isnull(B.InProc,0) 
From (Select CustName,CityID,TransactionCount=sum(Transactions) From SomeTable Group By CustName,CityID) A 
Left Join (Select CustName,CityID,InProc=sum(InProc) From SomeOtherTable Group By CustName,CityID) B 
Order By A.CustName,,A.CityID 
関連する問題