I have a couple of tables which are used to log user activity for an application. The tables looks something like this (pseudo code from memory, may not be syntactically correct):
create table activity (
sessionid uniqueidentifier not null,
created smalldatetime not null default getutcdate()
);
create table activity_details (
sessionid uniqueidentifier not null,
activity_description varchar(100) not null,
created smalldatetime not null default getutcdate()
);
My goal is to populate a summary table for reporting purposes that looks something like this:
create table activity_summary (
sessionid uniqueidentifier not null,
first_activity_desc varchar(100) not null,
last_activity_desc varchar(100) not null
);
First and last activity descriptions would be determined chronologically. My initial thought is to update the summary table like so:
truncate table activity_summary;
insert into activity_summary (sessionid)
select sessionid from activity;
update table activity_summary set
first_activity_desc = (select top 1 activity_desc from activity_detail where sessionid = as.sessionid order by created asc),
last_activity_summary = (select top 1 activity_desc from activity_detail where sessionid = as.sessionid order by created desc)
from activity_summary as;
However, this seems incredibly verbose and unnecessary to me. I'm just not sure how to shrink it down. My gut feel is that I could do it somehow all within the insert statement, but I'm stumped. Any suggestions?