Search code examples
sqlsql-servert-sqlthreshold

T-SQL Calculate threshold from a recordset


I have the following result set :

    ContentSendId ContentId   NewsletterId Position    IsConditionMatch SendDate                NumberOfSends IsSendValid
    ------------- ----------- ------------ ----------- ---------------- ----------------------- ------------- -----------
    1             100001      51           1           0                2011-05-14 00:00:00.000 200           0
    2             100001      51           1           0                2011-05-13 00:00:00.000 300           0
    3             100001      51           1           0                2011-05-14 00:00:00.000 100           0
    4             100001      51           1           0                2011-05-13 00:00:00.000 200           0

I need to run a calculation in T-SQL where if given a threshold value a record should get inserted (into a temp table) and any values outside the threshold should be ignored

So in this example lets say the threshold value is 500, the first record and the second record should get inserted.

EDIT : Running total is something to take care of in this scenario, so for example (above example updated) in the above scenario the temp table should insert 1st and 2nd record and stop since the threshold of 500 has been met.


Solution

  • select t1.ContentSendId, t1.ContentId, t1.NewsletterId, t1.Position, t1.IsConditionMatch, t1.SendDate, t1.NumberOfSends, t1.IsSendValid 
    into #t
    from yourtable t1
        inner join yourtable t2 on t1.ContentSendId>=t2.ContentSendId
    group by t1.ContentSendId, t1.ContentId, t1.NewsletterId, t1.Position, t1.IsConditionMatch, t1.SendDate, t1.NumberOfSends, t1.IsSendValid 
    having SUM(t2.NumberOfSends) < @threshold