有几种方法可以做到这一点。下面的示例使用自联接。每条记录都加入到上个月同一客户的记录中。
样本数据
/* 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 及更高版本具有LAG和LEAD函数,允许您通过不同的方法执行相同的操作。
/* 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 子句中重用计算,而无需重新输入逻辑。