[英]SQL Server SUM of values in column counted 3 different ways in the same output
I'm trying to find the right way to write a query to obtain the following dataset: 我试图找到正确的方法来编写查询以获取以下数据集:
CustName CityID TransactionCount Complete InProc
Hammertown 10001 200 50 150
SportsAuth 10002 10 1 9
"Complete" is a smaller set of TransactionCount, it should be the sum of TransactionCount when another column not shown (Format) is equal to: “完成”是较小的TransactionCount集,当未显示的另一列(格式)等于:时,它应该是TransactionCount的总和:
having [format]=23
or [format]=25
or [format]=38
or [format]>=400 and [format]<=499
or [format]>=800 and [format]<=899
"InProc" should then be the remainder of the TransactionCount value. 然后,“ InProc”应该是TransactionCount值的其余部分。 So far I've come up with the following:
到目前为止,我已经提出了以下建议:
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
This currently outputs the following data: 当前将输出以下数据:
CustName CityID InProc
Hammertown 10001 147
Hammertown 10001 1
Hammertown 10001 1
Hammertown 10001 1
SportsAuth 10002 4
SportsAuth 10002 4
SportsAuth 10002 1
So not only am I not getting 1 result back for each customer, but I don't know how I would add the other 2 columns in without breaking this query. 因此,不仅我没有为每个客户获得1个结果,而且我不知道如何在不破坏此查询的情况下添加其他2列。 Whatever help I can get would be greatly appreciated.
我能得到的任何帮助将不胜感激。
Assuming you can get the two sub-sets by CustName and CityID (your example is not that clear) . 假设您可以通过CustName和CityID获得两个子集(您的示例不清楚)。 A simple join can pull them together.
一个简单的连接可以将它们组合在一起。 In the example below.
在下面的示例中。 Alias A would be the primary summary and Alias B with be the in-process
别名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.