Wednesday, 15 February 2012

sql server 2012 - Running the same query over a range of values -



sql server 2012 - Running the same query over a range of values -

i have 3 tables, people, membership, , clubs. want find out 5 year period has had number of sign-ups. i'm hearing there no loops in sql server 2012 how can this? thanks. this:

select count(*) membership membership.date>=x-01-01 , membership.date<x+10-12-31

you can simulate loop while , cursor in sql server. has crazy overhead compared oracle's for. anytime think using loop in sql server doing wrong.

your problem can solved recursive cte , join:

;with periods ( select cast('2000-01-01' date) startdate, cast('2004-12-31' date) enddate union select dateadd(year,1,startdate), dateadd(year,1,enddate) periods startdate < '2014-01-01' ) select p.startdate, p.enddate, count(m.*) memberships m inner bring together periods p on m.date between p.startdate , p.enddate grouping p.startdate, p.enddate

the with statement defines recursive cte containing 5-year periods each year between 2000 , 2014. adjust needed.

sql-server-2012

No comments:

Post a Comment