简体   繁体   中英

SQL to group and aggregate based on different record-types

Considering the below table structure

ADateTime    AGroupName   ARecordType   AValue
==========   ==========   ===========   ======
2013-01-01   Ninjas       A             10
2013-01-01   Ninjas       B             5
2013-01-01   Ninjas       C             2
2013-01-01   Ninjas       D             1
2013-01-01   Ninjas       E             0
2013-01-01   Clowns       A             8
2013-01-01   Clowns       B             4
2013-01-01   Clowns       E             1
2013-01-08   Ninjas       A             7
2013-01-08   Ninjas       B             3
2013-01-08   Ninjas       E             1
2013-01-08   Clowns       A             4
2013-01-08   Clowns       B             3

I need to calculate 2 values (CalcVal1 and CalcVal2) for each combination of ADateTime and AGroupName. In other words, I need to GROUP BY ADateTime and AGroupName (that's the easy part).

NOTE: As you can see from the sample data, there is no guarantee that a certain record-type will exist for a given grouping... so outer join and coalesce if/where necessary!

What I'm trying to figure out is how to calculate CalcVal1 and CalcVal2 depending on the values of ARecordType. Below are the specifications for CalcVal1 and CalcVal2...

  1. CalcVal1 is the (SUM of AValue where ARecordType='A')
  2. CalcVal2 is the (SUM of AValue where ARecordType IN ('B','C')) MINUS the (SUM of AValue where ARecordType IN ('D','E'))

The result set I expect is

ADateTime    AGroupName   CalcVal1   CalcVal2
==========   ==========   ========   ========
2013-01-01   Ninjas       10            6
2013-01-01   Clowns       8             3
2013-01-08   Ninjas       7             2
2013-01-08   Clowns       4             3

I'm using T-SQL on SQL-Server 2005. SQLs or Stored Procedures welcome. TIA, I'm getting too old for this and it's about time they made me the CTO! (;-D)

You can do this with conditional aggregation, almost the way you described it:

select ADateTime, AGroupName,
       SUM(case when ARecordType = 'A' then AValue else 0 end) as CalcVal1,
       (SUM(case when ARecordType in ('B', 'C') then AValue else 0 end) -
        SUM(case when ARecordType in ('D', 'E') then AValue else 0 end)
       ) as CalcVal2
from t
group by ADateTime, AGroupName

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM