SQL Server 2008查询总结日期,如果达到阈值则标记为0

时间:2014-02-20 13:06:30

标签: sql sql-server-2008 sum

我在SQL Server 2008中有一个表;

DateStamp       QTY
1/1/2014        1
1/5/2014        2
1/6/2014        3
1/7/2014        2
1/8/2014        3
1/11/2014       1
1/20/2014       6
1/21/2014       4
1/25/2014       1
1/26/2014       2
1/28/2014       3
1/29/2014       2
2/2/2014        3
2/3/2014        1
2/7/2014        6
2/8/2014        4
2/15/2014       1
2/19/2014       2
2/20/2014       3
2/23/2014       2

我希望得到如下结果:

总和直到达到最小阈值让我们说10为例(

然后显示并重新开始(从零开始求和)

在结果之间应该是类似的结果;

DateStamp       QTY     SUBtotal
1/1/2014        1       
1/5/2014        2       
1/6/2014        3       
1/7/2014        2       
1/8/2014        3       11
1/11/2014       1       
1/20/2014       6       
1/21/2014       4       11
1/25/2014       1       
1/26/2014       2       
1/28/2014       3       
1/29/2014       2       
2/2/2014        3       11
2/3/2014        1       
2/7/2014        6       
2/8/2014        4       11
2/15/2014       1       
2/19/2014       2       
2/20/2014       3       
2/23/2014       2       
2/26/2014       1       
3/1/2014        1       10

最终结果

DateStamp       total
1/8/2014        11
1/21/2014       11
2/2/2014        11
2/8/2014        11
3/1/2014        10

谢谢

理查德

编辑:(来自评论)

SELECT 
    t0.*, 
    SUM(t1.qty), 
    CASE 
        WHEN SUM(t1.qty) > 5 THEN SUM(t0.qty) ELSE 0 
    END AS subtotal
FROM 
    (SELECT 
        *, 
        ROW_NUMBER() OVER(ORDER BY DATESTAMP asc) AS RowNumber
     FROM dbo.DATESEARCH) AS t0 
INNER JOIN
     (SELECT 
         *, 
         ROW_NUMBER() OVER(ORDER BY DATESTAMP asc) AS RowNumber
      FROM dbo.DATESEARCH) AS t1 ON t1.RowNumber <= t0.RowNumber
GROUP BY 
    t0.RowNumber, t0.DATESTaMP, t0.qty
HAVING 
    SUM(t1.qty) > 10 

1 个答案:

答案 0 :(得分:0)

我同意Gordon的观点,在单个SQL语句中累积总和很容易。您需要的可能是一些更高级的TSQL。不是最佳,但至少可以为您的服务器省去一些往返。

DECLARE @result TABLE (datestamp DATETIME, qty INT)
DECLARE @datestamp DATETIME, @qty INT, @qty_sum INT = 0 
DECLARE iterator CURSOR LOCAL FAST_FORWARD FOR 
    SELECT datestamp,qty FROM mytable ORDER BY datestamp

OPEN iterator
FETCH NEXT FROM iterator INTO @datestamp,@qty
WHILE @@FETCH_STATUS = 0 BEGIN
    IF (@qty + @qty_sum > 10) BEGIN
        INSERT @result VALUES (@datestamp, @qty + @qty_sum)
        SET @qty_sum = 0
    END ELSE BEGIN
        SET @qty_sum += @qty
    END

    FETCH NEXT FROM iterator INTO @datestamp,@qty
END
IF (@qty_sum > 0) BEGIN
    INSERT @result VALUES (@datestamp, @qty_sum)
END 
CLOSE iterator
DEALLOCATE iterator

SELECT * FROM @result ORDER BY datestamp