Question : SQL query - date usage rate / usage rate period

I have a view that returns data looking much like this

ItemID     TranDate          ItemUsageRate    ItemUsageRatePeriodDays
1000       Jan 1, 2010          2                         4
1000       Jan 3, 2010          2                         4
1000       Jan 4, 2010          2                         4

1000       Jan 8, 2010          2                         4
1000       Jan 10, 2010        2                         4
2000       Feb 1, 2010          1                         1
2000       Feb 3, 2010          1                         1
2000       Feb 5, 2010          1                         1
2000       Feb 5, 2010          1                         1


I'd like to return only the records underlined above which violate the allowed usage rate per usagerateperiod. I think a cursor in sql might do the trick but i could not get it working. Please provide sample code of how this can be done

Answer : SQL query - date usage rate / usage rate period

Select returns you  itemid, start date and end date of each overusage period. Just join it with original table as
"on t.itemID = violations.itemId and t.tranDate between violations.dstart and violations.dEnd "


select t.* from #tbl t
join (
select t.itemID, dusage.tranDate,r.usageRate, r.usageDays, min(t.tranDate) dStart, max(t.tranDate) dEnd, count(*) cnt, sum(usePerDay)  usePerDay
from #tbl t
join #usageRetrictions r on t.itemID=r.itemID
join (select itemID, datediff(dd, tranDate, getdate()) ddiff,  min(tranDate) tranDate,  count(*) as usePerDay from #tbl group by itemID, datediff(dd, tranDate, getdate())
      ) dusage
on r.itemID = dusage.itemID and t.tranDate between dusage.tranDate and dateadd(dd, r.usageDays,dusage.tranDate)
group by  t.itemID, dusage.tranDate,r.usageRate, r.usageDays
having sum(usePerDay)>r.usageRate
) violations
on t.itemID = violations.itemId and t.tranDate between violations.dstart and violations.dEnd
Random Solutions  
 
programming4us programming4us