jeudi 23 juin 2016

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:

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. 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. Whatever help I can get would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire