I have a database in the following format:
ID TYPE SUBTYPE COUNT MONTH
1 A Z 1 7/1/2008
1 A Z 3 7/1/2008
2 B C 2 7/2/2008
1 A Z 3 7/2/2008
Can I use SQL to convert it into this:
ID A_Z B_C MONTH
1 4 0 7/1/2008
2 0 2 7/2/2008
1 0 3 7/2/2008
So, the TYPE
, SUBTYPE
are concatenated into new columns and COUNT
is summed where the ID
and MONTH
match.
Any tips would be appreciated. Is this possible in SQL or should I program it manually?
The database is SQL Server 2005.
Assume there are 100s of TYPES
and SUBTYPES
so and 'A' and 'Z' shouldn't be hard coded but generated dynamically.
SQL Server 2005 offers a very useful PIVOT and UNPIVOT operator which allow you to make this code maintenance-free using PIVOT and some code generation/dynamic SQL
You change requirements more than our marketing team! If you want it to be dynamic you'll need to fall back on a sproc.