Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is a solution:</p> <pre><code>declare @Query_Start_Date date= '2011-01-01' declare @Query_End_Date date = '2011-09-30' declare @D_Fee_Basis table(F_Fee_Item int) insert @D_Fee_Basis values(1) insert @D_Fee_Basis values(2) insert @D_Fee_Basis values(3) declare @F_Fee_Item table(Fee_Item_ID int, Fee_Basis_ID int,Start_Date date,End_Date date) insert @F_Fee_Item values(1,1,'2011-01-01','2011-03-31') insert @F_Fee_Item values(2,1,'2011-04-01','2011-06-30') insert @F_Fee_Item values(3,2,'2011-01-01','2011-03-31') insert @F_Fee_Item values(4,2,'2011-05-01','2011-06-30') ;with a as (-- find all days between Start_Date and End_Date select @Query_Start_Date d union all select dateadd(day, 1, d) from a where d &lt; @Query_end_Date ), b as (--find all unused days select a.d, F_Fee_Item Fee from a, @D_Fee_Basis Fee where not exists(select 1 from @F_Fee_Item where a.d between Start_Date and End_Date and Fee.F_Fee_Item = Fee_Basis_ID) ), c as (--find all start dates select d, Fee, rn = row_number() over (order by fee, d) from b where not exists (select 1 from b b2 where dateadd(day,1, b2.d) = b.d and b2.Fee= b.Fee) ), e as (--find all end dates select d, Fee, rn = row_number() over (order by fee, d) from b where not exists (select 1 from b b2 where dateadd(day,-1, b2.d) = b.d and b2.Fee= b.Fee) ) --join start dates with end dates select c.Fee Fee_Basis_ID, c.d Start_Date, e.d End_Date from c join e on c.Fee = e.Fee and c.rn = e.rn option (maxrecursion 0) </code></pre> <p>Link for result: <a href="http://data.stackexchange.com/stackoverflow/q/114193/" rel="nofollow">http://data.stackexchange.com/stackoverflow/q/114193/</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload