Here is the scenario: I have a table that records the user_id, the module_id, and the date/time the module was viewed.
eg.
Table: Log
------------------------------
User_ID Module_ID Date
------------------------------
1 red 2001-01-01
1 green 2001-01-02
1 blue 2001-01-03
2 green 2001-01-04
2 blue 2001-01-05
1 red 2001-01-06
1 blue 2001-01-07
3 blue 2001-01-08
3 green 2001-01-09
3 red 2001-01-10
3 green 2001-01-11
4 white 2001-01-12
I need to get a result set that has the user_id as the 1st column, and then a column for each module. The row data is then the user_id and the count of the number of times that user viewed each module.
eg.
---------------------------------
User_ID red green blue white
---------------------------------
1 2 1 2 0
2 0 1 1 0
3 1 2 1 0
4 0 0 0 1
I was initially thinking that I could do this with PIVOT, but no dice; the database is a converted SQL Server 2000 DB that is running in SQL Server 2005. I'm not able to change the compatibility level, so pivot is out.
The other catch is that the modules will vary, and it isn't feasible to re-write the query every time a module is added or removed. This means that I can't hard-code in the modules because I don't know in advance which will and will not be installed.
How can I accomplish this?
PIVOT can be simulated with CASE and GROUP BY
Of course this doesn't work if the modules vary (as stated in the question) but then, PIVOT has the same problem.
Dynamically generating some sql overcomes this problem but this solution smells a bit!
Note that this may be vulnerable to sql-injection if the module id data can't be trusted.
Using MySQL I did this:
create table Log (User_ID mediumint, Module_ID CHAR(5), dte CHAR(10));
load data infile 'Log_Table.sql' INTO TABLE Log FIELDS TERMINATED BY ',';
Pivot:
Hope this helps.
I believe characteristic functions are what you want.