返回比较列的百分比值的差异

时间:2015-03-21 09:46:53

标签: sql-server function tsql

我有一张有10,000张富临记录的专栏。 值为:ID PK, OwingValue 示例数据

ID   OwingValue
1    123.2
2    123.4
3    123.5
4    123.6
5    123.7
6    140.2
7    140.3

对于与前一记录差异超过0.7%的给定列,返回差异较大的记录。

在这种情况下,结果将是第7列,因为(第6列OwingValue - 第5列dueValue)乘以 到100将给出1.650%,高于我们的0.7%的门槛 我需要一个sql while loop或curso来帮助我解决这个问题。

先谢谢

3 个答案:

答案 0 :(得分:1)

试试这个:

DECLARE @t TABLE ( ID INT, V MONEY )

INSERT  INTO @t
VALUES  ( 1, 123.2 ),
        ( 2, 123.4 ),
        ( 3, 123.5 ),
        ( 4, 123.6 ),
        ( 5, 123.7 ),
        ( 6, 140.2 ),
        ( 7, 140.3 )

SELECT  t1.ID
FROM    @t t1
        JOIN @t t2 ON t1.ID = t2.ID + 1
        JOIN @t t3 ON t2.ID = t3.ID + 1
WHERE   ( t2.v - t3.V ) / t3.V * 100 > 0.7

输出:

ID
7

如果你的身份证有差距,那么:

DECLARE @t TABLE ( ID INT, V MONEY )

INSERT  INTO @t
VALUES  ( 1, 123.2 ),
        ( 2, 123.4 ),
        ( 3, 123.5 ),
        ( 5, 123.6 ),
        ( 9, 123.7 ),
        ( 16, 140.2 ),
        ( 27, 140.3 );


WITH    cte
          AS ( SELECT   ROW_NUMBER() OVER ( ORDER BY ID ) AS ID ,
                        V
               FROM     @t
             )
    SELECT  t1.ID
    FROM    cte t1
            JOIN cte t2 ON t1.ID = t2.ID + 1
            JOIN cte t3 ON t2.ID = t3.ID + 1
    WHERE   ( t2.v - t3.V ) / t3.V * 100 > 0.7

答案 1 :(得分:0)

尝试使用LAG功能,

SELECT ID,
       OWING_VALUE,
       LAG,
       ( OWING_VALUE - LAG ) / OWING_VALUE * 100 AS INCREASE_PERCENT
FROM   (SELECT *,
               Row_number()
                 OVER (
                   ORDER BY ID) AS RN,
               CASE
                 WHEN Row_number()
                        OVER (
                          ORDER BY ID) = 1 THEN OWING_VALUE
                 ELSE Lag(OWING_VALUE, 1, 0)
                        OVER(
                          ORDER BY ID )
               END              AS LAG
        FROM   #Your_Table)A
WHERE  ( OWING_VALUE - LAG ) / OWING_VALUE * 100 > 0.7 

答案 2 :(得分:0)

使用lag(),但这是最简单的方法:

select t.*
from (select t.*,
             lag(owingvalue) over (order by id) as prev_owingvalue
      from table t
     ) t
where owingvale >= 1.07 * prev_owingvalue;

这会将“当前”和上一个值放在同一行输出中。