Are your periods always 6 months in length starting on either January or June? Or do you want periods that vary according to the current date (i.e., if you run the query in June it will show you totals for Dec ~ May and June ~ Nov? Assuming the
latter:
set nocount on;
create table #t1 (
tdate date not null,
amount decimal(10,2) not null);
insert #t1(tdate, amount) values ('20120625', 10), ('20120805', 20), ('20121224', 5),
('20130501', 10), ('20130701', 100), ('20120531', 1000), ('20130101', 2), ('20120701', 7);
select * from #t1 order by tdate;
go
declare @target date;
declare @t1 date, @t2 date;
set @target = CURRENT_TIMESTAMP;
set @t1 = dateadd(day, -(datepart(day, @target)) + 1, @target);
select @target, @t1;
/* If I run the query today, it will show a sum in column 1 based on Jan-june (june beingthe last 'full' month).
In column 2 it will show a sum for the months july-dec for LAST year. */
select tdate,
case when tdate < @t1 and tdate >= dateadd(month, -6, @t1) then amount else 0 end as x,
case when tdate < dateadd(month, -6, @t1) and tdate >= dateadd(month, -12, @t1) then amount else 0 end as y
from #t1 order by tdate;
drop table #t1;
You might find a calendar table very useful for such queries. Search in the forums for suggestions about creating one.