获取两个不同日期的两个数字之间的百分比变化

时间:2015-03-09 08:02:40

标签: sql-server

我的数据格式如下:

run_date    test_alias  test_value
12/23/2014    1           12
11/22/2014    1           5
1/20/2015     1           7
2/20/2015     1           9

12/19/2014    2           12.1
2/19/2015     2           12.2
1/18/2015     2           12.3
11/17/2014    2           12.4

2/13/2015     3           4
1/13/2015     3           5
12/13/2014    3           7
11/13/2014    3           8

如何获取记录的ID,其中偏离百分比在今天的最后3个月内在50%到80%之间。在这种情况下,应该选择ID 3和1,因为对于id 3,最后3个月的值是4,5和7.在这种情况下,偏离率为7-4 = 3/4(75%),在50%和80%之间

任何帮助都会非常棒

1 个答案:

答案 0 :(得分:0)

试试这个解决方案。如果您有任何疑问,请询问:

DECLARE @t TABLE ( ID INT, D DATE, V MONEY )

INSERT  INTO @t
VALUES  ( 1, '20141223', 12 ),
        ( 1, '20141122', 5 ),
        ( 1, '20150120', 7 ),
        ( 1, '20150220', 9 ),
        ( 2, '20141219', 12.1 ),
        ( 2, '20150219', 12.2 ),
        ( 2, '20150118', 12.3 ),
        ( 2, '20141117', 12.4 ),
        ( 3, '20150213', 4 ),
        ( 3, '20150113', 5 ),
        ( 3, '20141213', 7 ),
        ( 3, '20141113', 8 );
WITH    cte
          AS ( SELECT   ID ,
                        D ,
                        V ,
                        ROW_NUMBER() OVER ( PARTITION BY ID ORDER BY D DESC ) AS RN
               FROM     @t
             )
    SELECT  c1.ID ,
            ( c1.V - c2.V ) / c2.V AS V
    FROM    cte c1
            JOIN cte c2 ON c2.ID = c1.ID
                           AND c2.RN = 1
    WHERE   c1.RN = 3
            AND ( c1.V - c2.V ) / c2.V BETWEEN 0.5 AND 0.8

输出:

ID  V
3   0.75