I am trying to aggregate data from one table into another. I've inherited this project; I did not design this database nor will I be able to change its format.
The [RawData] table will have 1 record per account, per ChannelCodeID. This table (where I currently have data) has the following fields:
[Account] int
[ChannelCodeID] int
[ChannelCode] varchar(10)
The [AggregatedData] table will have 1 record per account. This table (into which I need to insert data) has the following fields:
[Account] int
[Count] int
[Channel1] int
[Channel2] int
[Channel3] int
[Names] varchar(250)
For example, I might have the following records in my [RawData] table:
Account ChannelCodeID ChannelCode
12345 2 ABC
12345 4 DEF
12345 6 GHI
54321 2 ABC
54321 6 GHI
99999 2 ABC
And, after aggregating them, I would need to produce the following records in my [AggregatedData] table:
Account Count Chanel1 Channel2 Channel3 Names
12345 3 2 4 6 ABC.DEF.GHI
54321 2 2 6 0 ABC.GHI
99999 1 2 0 0 ABC
As you can see, the count is how many records exist in my [RawData] table, Channel1 is the first ChannelCodeID, Channel2 is the second, and Channel3 is the third. If there are not enough ChannelCodeIDs from my [RawData] table, extra Channel columns get a '0' value. Furthermore, I need to concatenate the 'ChannelCode' column and store it in the 'Names' column of the [AggregatedData] table, but (obviously) if there is only one record, I don't want to add the '.'
I can't figure out how to do this without using a cursor and a bunch of variables - but I'm guessing there HAS to be a better way. This doesn't have to be super-fast since it will only run once a month, but it will have to process at least 10-15,000 records each time.
Thanks in advance...
EDIT:
ChannelCodes and ChannelCodeIDs map directly to each other and are always the same. For example, ChannelCodeID 2 is ALWAYS 'ABC'
Also, in the [AggregatedData] table, Channel1 is ALWAYS the lowest value, although this is incidental.