计算从N到1 SQL的范围编号

时间:2016-04-06 03:08:32

标签: sql sql-server sql-server-2008 tsql

我有以下代码:

DECLARE @StartDate DATE = '2016-01-01'
        ,@EndDate  DATE = '2016-12-31'
        ,@MaxValue  float  = 96.0
        ,@MinValue float = 95.0
        ,@pValue float =  0.000972222222222222
        ,@pValue2 float =  0.002

;WITH ctetest AS 
    (
        SELECT      @StartDate AS CDate, @MaxValue AS Case1, @MaxValue as Case2, 
                    0 as OLNo
        UNION ALL
        SELECT      dateadd(day,1,CDate) ,(1-@pValue) * Case1, 
                    CASE WHEN Case2 < @MinValue THEN 96 ELSE (1-@pValue2) * Case2 END,
                    OLNo + (CASE WHEN Case2 < @MinValue THEN 1 ELSE 0 END)
        FROM        ctetest 
        WHERE       dateadd(day,1,CDate)<=@EndDate
        )
        SELECT      * 
        INTO        #t1 
        FROM        ctetest OPTION (MAXRECURSION 0)


SELECT  @MinValue Val, MAX(OLNo) * 24 * @MinValue tRes, SUM((Case2 * 24)) Res1, 
        (SUM((Case2 * 24))) - (MAX(OLNo) * 24 * @MinValue) Res2
FROM    #t1

结果应该是:

----------------------------------------------
Val     tRes         Res1                Res2   
----------------------------------------------
95.0    118560       838244.195613986    719684.195613986

我的问题是,我怎样才能得到一个结果(上图),范围编号从@MinValue开始到1.如下表所示:

----------------------------------------------
Val     tRes         Res1                Res2   
----------------------------------------------
95.0    118560       838244.195613986    719684.195613986
94.0    67680        834131.776802389    766451.776802389
93.0    ??????       ????????????????    ????????????????
ff.
1.0     ??????       ????????????????    ????????????????

我想将此代码放在我的商店程序中。 有谁知道如何实现这一目标?真的很感激。
谢谢。

1 个答案:

答案 0 :(得分:2)

更改:

  • 添加了min_value CTE
  • 将MinValue添加到ctetest
  • 在原始查询中将@MinValue更改为MinValue
  • 最终查询 - GROUP BY

查询

; WITH 
min_value AS   -- Added this
(
    SELECT      MinValue =  @MinValue
    UNION ALL
    SELECT      MinValue = MinValue - 1
    FROM        min_value
    WHERE       MinValue > 0
),
ctetest AS 
(
        SELECT      @StartDate AS CDate, @MaxValue AS Case1, @MaxValue as Case2,
                    0 as OLNo, MinValue  
        FROM        min_value            -- added this
        UNION ALL
        SELECT      dateadd(day,1,CDate) ,(1-@pValue) * Case1, 
                    CASE WHEN Case2 < MinValue THEN 96 ELSE (1-@pValue2) * Case2 END,
                    OLNo + (CASE WHEN Case2 < MinValue THEN 1 ELSE 0 END), MinValue
        FROM        ctetest 
        WHERE       dateadd(day,1,CDate)<=@EndDate
)
SELECT  MinValue Val, 
        MAX(OLNo) * 24 * @MinValue tRes, SUM((Case2 * 24)) Res1, 
        (SUM((Case2 * 24))) - (MAX(OLNo) * 24 * @MinValue) Res2
FROM    ctetest 
GROUP BY MinValue           -- added this
ORDER BY MinValue DESC
OPTION  (MAXRECURSION 0)