2012-10-04 97 views
-1

我有以下结果集:从记录的T-SQL计算门槛

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 

我需要运行在T-SQL中的计算,其中,如果给定的阈值的记录应该得到插入(到一个临时表)和阈值之外的任何值应该因此,在这个例子中可以忽略

可以说阈值是500,第一个记录和第二个记录应该得到插入。

编辑: 在这种情况下运行总数是需要注意的,例如(上面的示例更新)在上述情况下,临时表应该插入第一个和第二个记录并停止,因为已达到阈值500 。

+2

你能分享没有用的sql语句吗? – rene

+0

SQL Server 2005,2008或2012?它可能会影响解决方案的制定方式。适用于SQL 2008的答案可能不适用于SQL 2012,因为新版本对于某些内容具有一流的构造,例如,运行总计,而与旧版本中,你必须拿出创造性与最佳的解决方案 –

+0

SQL Server 2008中 –

回答

1
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 
+0

更新后的问题更多的细节。 –

+1

与多个SQL :) – podiluska

0

看来你只是想过滤结果集。

SELECT * FROM t1 
GROUP BY SendDate 
HAVING SUM(NumberOfSends) >= 500 
+0

对不起增加了更多的解释,并提高我的例子结果集更新的答案,运行总计是重要的考虑因素。 –