列中值的SQL Server SUM在同一输出中计算了3种不同的方式

时间:2016-06-22 18:43:34

标签: sql sql-server

我正在尝试找到编写查询以获取以下数据集的正确方法:

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列。无论我能得到什么帮助都将不胜感激。

2 个答案:

答案 0 :(得分:0)

假设您可以通过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

答案 1 :(得分: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