簡體   English   中英

列中值的SQL Server SUM在同一輸出中計數了3種不同的方式

[英]SQL Server SUM of values in column counted 3 different ways in the same output

我試圖找到正確的方法來編寫查詢以獲取以下數據集:

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

然后,“ InProc”應該是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列。 我能得到的任何幫助將不勝感激。

假設您可以通過CustName和CityID獲得兩個子集(您的示例不清楚)。 一個簡單的連接可以將它們組合在一起。 在下面的示例中。 別名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
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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM