• Something like this

    DECLARE@startdate DATE

    DECLARE@enddate DATE

    SET@startdate = '20130701'

    SET@enddate = '20130703'

    SELECTT.ITEM, DATEADD(DAY, D.number, @startdate) AS Dt, SUM(T.QTY) AS QTY

    FROM@t AS T

    CROSS APPLY(

    SELECT*

    FROMmaster.dbo.spt_values AS sv -- You can use a Tally table instead of this

    WHEREsv.type = 'P' AND sv.number <= DATEDIFF(DAY, @startdate, @enddate)

    AND(

    ( DATEADD(DAY, sv.number, @startdate) >= T.CREATED AND T.ENDS IS NULL ) OR

    ( DATEADD(DAY, sv.number, @startdate) >= T.CREATED AND DATEADD(DAY, sv.number, @startdate) < T.ENDS )

    )

    ) AS D

    GROUP BY T.ITEM, DATEADD(DAY, D.number, @startdate)

    ORDER BY Dt, ITEM

    You can use Tally tables instead of the spt_values tables that I have used

    Please check the link below for more information on Tally Tables

    http://www.sqlservercentral.com/scripts/Advanced+SQL/62486/

    I think the results that you have given are incorrect

    There are 2 rows for ITEM5 in your sample data, one of them gets discontinued on 20130630

    INSERT INTO @t (ITEM, QTY, CREATED, ENDS, USERID) SELECT 'ITEM 5',1,'28-05-2013 13:17:00',NULL,2

    INSERT INTO @t (ITEM, QTY, CREATED, ENDS, USERID) SELECT 'ITEM 5',1,'28-05-2013 10:10:00','30-06-2013 11:45:00',4

    So, its incorrect when you said that it has been discontinued completely.


    Kingston Dhasian

    How to post data/code on a forum to get the best help - Jeff Moden
    http://www.sqlservercentral.com/articles/Best+Practices/61537/