In Oracle you can do something like that :
with t as
(
select 23 as account,1 as amount,to_date('01/01/2009 09:00:00', 'DD/MM/YYYY HH24:MI:SS') as datetime from dual
union select 23,2,to_date('01/01/2009 10:00:00', 'DD/MM/YYYY HH24:MI:SS')from dual
union select 23,3,to_date('01/01/2009 11:00:00', 'DD/MM/YYYY HH24:MI:SS')from dual
union select 23,4,to_date('01/01/2009 12:00:00', 'DD/MM/YYYY HH24:MI:SS')from dual
union select 23,5,to_date('01/01/2009 13:00:00', 'DD/MM/YYYY HH24:MI:SS')from dual
union select 23,1,to_date('01/02/2009 10:00:00', 'DD/MM/YYYY HH24:MI:SS')from dual
union select 23,2,to_date('01/02/2009 11:00:00', 'DD/MM/YYYY HH24:MI:SS')from dual
union select 23,2,to_date('01/02/2009 12:00:00', 'DD/MM/YYYY HH24:MI:SS')from dual
union select 23,1,to_date('01/02/2009 13:00:00', 'DD/MM/YYYY HH24:MI:SS')from dual
)
select account, trunc(datetime),
min(amount) keep (dense_rank first order by datetime asc) as opening_amount,
max(amount) keep (dense_rank first order by datetime desc) as closing_amount
from t
group by account, trunc(datetime)
Returns
ID Date opening_Amount closing_amount
23 01/01/2009 1 5
23 01/02/2009 1 1
But the keep analytic function doesn't seem to be in SQLServer... So my post is useless :o)
Edit 1: Ok, first try to simulate the keep function in SQL Server 2005, don't be too hard..
with t as
(
select 23 as account_id,1 as amount,cast('01/01/2009 10:00:00' as datetime) as date
union all select 23,2,cast('01/01/2009 11:00:00' as datetime)
union all select 23,3,cast('01/01/2009 12:00:00' as datetime)
union all select 23,1,cast('01/02/2009 10:00:00' as datetime)
union all select 23,2,cast('01/02/2009 11:00:00' as datetime)
union all select 23,3,cast('01/02/2009 12:00:00' as datetime)
union all select 23,2,cast('01/02/2009 13:00:00' as datetime)
union all select 23,1,cast('01/02/2009 14:00:00' as datetime)
)
select *
from
(
select account_id,
date,
amount,
min(date) over (partition by account_id, convert(varchar(8), date, 112) ) as open_date,
max(date) over (partition by account_id, convert(varchar(8), date, 112) ) as close_date
from t
) a
where open_date = date or close_date = date
A little ugly, but give the good result I think.