【问题标题】:Percentage variation between values in different months (SQL Server)不同月份值之间的百分比变化 (SQL Server)
【发布时间】:2016-02-25 10:56:08
【问题描述】:

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

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

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

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

提前致谢

【问题讨论】:

  • 那么在这个例子中,所有的行都应该返回?
  • 您使用的是哪个 SqlServer 版本?在 2012 年及以后,有用于此类查询的内置窗口函数。 2008 年及之前的版本是构建 agg 表,然后在它们之上进行查询。如果您提供数据示例,以及您希望结果集如何,这将有助于提出解决方案。

标签: sql sql-server tsql percentage variation


【解决方案1】:

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

样本数据

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

【讨论】:

    猜你喜欢
    • 2019-02-24
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    相关资源
    最近更新 更多