2

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

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

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% 的账户。

我使用什么代码来计算差异然后转换为百分比差异?

提前致谢

4

1 回答 1

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 子句中重用计算,而无需重新输入逻辑。

于 2016-02-25T12:44:39.753 回答