although i think a couple of the previous posts have covered it, here is my take
if the nr of possible events are know, ie yuo know there will be evt1,evt2 and evt3, you can do this quite simple using setbased (and standard) sql.
select person,
sum(case when event_id = 1 then 1 else 0 end) as cnt_event_1,
sum(case when event_id = 2 then 1 else 0 end) as cnt_event_2,
sum(case when event_id = 3 then 1 else 0 end) as cnt_event_3
from mytable
group by person
if it is not, and you are not using ms sql 2005 (which implements crosstab), or ms sql 2000 with an additional 3rd party crosstab xp, then you can either:
a) build a dynamic sql t obe executed via exec(@sql), or sp_executesql (ms specific). no need for cursors even, d oa coalesce with distinct to pick up the exact nr of events to match...
b) use a cursor (which almost always sucks, and tells you u probably did somethin wrong)
either way, the db will sort it out faster then taking the data out of there and process in some other language (i dont care what u guys say, datacentric processing win 9 out of 10 times).
need specifics, let me know
my 2 cents only,
FGE
if the nr of possible events are know, ie yuo know there will be evt1,evt2 and evt3, you can do this quite simple using setbased (and standard) sql.
select person,
sum(case when event_id = 1 then 1 else 0 end) as cnt_event_1,
sum(case when event_id = 2 then 1 else 0 end) as cnt_event_2,
sum(case when event_id = 3 then 1 else 0 end) as cnt_event_3
from mytable
group by person
if it is not, and you are not using ms sql 2005 (which implements crosstab), or ms sql 2000 with an additional 3rd party crosstab xp, then you can either:
a) build a dynamic sql t obe executed via exec(@sql), or sp_executesql (ms specific). no need for cursors even, d oa coalesce with distinct to pick up the exact nr of events to match...
b) use a cursor (which almost always sucks, and tells you u probably did somethin wrong)
either way, the db will sort it out faster then taking the data out of there and process in some other language (i dont care what u guys say, datacentric processing win 9 out of 10 times).
need specifics, let me know
my 2 cents only,
FGE
Comment