T-SQL - Track occurrences over time

。_饼干妹妹 提交于 2019-12-06 04:06:47

The logic in your SQL is mostly correct, you have just implemented it poorly for how SQL likes to do things. Starting with your Dates table as you have done already, rather than doing a sub-select for each row of data, change your logic to a join and you are there:

select d.DateKey
      ,count(m.MembershipID) as MembershipCount
from DIM.[Date] as d
    left join Memberships as m
        on(d.DateKey between m.ValidFromDateKey and m.ValidToDateKey)
where d.CalendarYear = 2016
group by d.DateKey
order by d.DateKey;

What you may want to be careful of is identifying which memberships are to be counted on each day. For example, if your date is 2006-05-09 should MembershipID 0001 be included as it ends that day?

The question is essentially, are you counting the number of Memberships that were active at any point during the entire day, or just those that were active at a particular time, say the start or the end of the day?

Then repeat this thought process for your ValidFromDate values.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!