不同月份的值之间的百分比变化(SQL Server)

时间:2016-02-25 10:56:08

标签: sql sql-server tsql percentage variation

我是初学者,很抱歉,如果这很简单。

我每个月都有一个表格,每个帐户都有一行,所以在我的表格中我为同一个帐户设置了多行,但每行只有一行,如下所示:

Month    AccountID   Score
---------------------------
Jan-16   xxxxx1      100
Jan-16   xxxxx2      200
Jan-16   xxxxx3      150
Feb-16   xxxxx1      120
Feb-16   xxxxx2      150
Feb-16   xxxxx3      180

我需要选择有>的帐户每月得分变化10%。

我使用什么代码来计算差异,然后转换为%差异?

提前致谢

1 个答案:

答案 0 :(得分:0)

有几种方法可以做到这一点。以下示例使用自联接。每条记录都会加入上个月同一客户的记录。

示例数据

/* I've used a table variable to make sharing the example data
 * easier.  You could also use SQL Fiddle or Stack Data Explorer.
 */
DECLARE @Score TABLE
    (
        [Month]     DATE,
        AccountId   NVARCHAR(50),
        Score       INT
    )
;

-- Sample data taken from OP.
INSERT INTO @Score  
    (
        [Month],
        AccountId,
        Score
    )
VALUES
    ('2016-01-01', 'xxxxx1', 100),
    ('2016-01-01', 'xxxxx2', 200),
    ('2016-01-01', 'xxxxx3', 150),
    ('2016-02-01', 'xxxxx1', 120),
    ('2016-02-01', 'xxxxx2', 150),
    ('2016-02-01', 'xxxxx3', 180)
;

自联接允许您将不同行中出现的值进行比较。 SQL Server 2012及更高版本具有LAGLEAD函数,允许您通过不同的方法执行相同的操作。

/* Using a self join.
 */
SELECT
    monthCurr.[Month],
    monthCurr.AccountId,
    monthCurr.Score         AS CurrentScore,
    monthLast.Score         AS PreviousScore,
    calc.Variance
FROM
    @Score AS monthCurr
        INNER JOIN @Score AS monthLast          ON  monthLast.AccountId     = monthCurr.AccountId
                                                AND monthLast.[Month]       = DATEADD(MONTH, 1, monthCurr.[Month])
        CROSS APPLY
            (
                /* Usign cross apply allows us to use Variance multiple times in the main query
                 * without rewritting the logic.
                 */
                SELECT
                    (monthCurr.Score - monthLast.Score) / CAST(monthLast.Score AS DECIMAL(18, 2)) * 100 AS Variance
            ) AS calc
WHERE
    calc.Variance BETWEEN -20 AND -10
;

如果您将分数存储为整数,则应考虑使用CAST转换为小数。带小数的除法包括整数(整数)的舍入更少。

我使用了CROSS APPLY来计算方差。这允许我在SELECT和WHERE子句中重用计算,而无需重新输入逻辑。