我目前有一个表(预测),第一列包含两种类型的数据,即实际数据和预测数据。我想根据两个预测之间的月份来找到差异。该表如下所示:
Data | Product | Forecast M1 | Forecast M2 | Forecast M3
Actual A 13 16 18
Actual B 22 24 30
Forecast A 15 14 21
Forecast B 24 25 26
我想查询一个基于月比较两种产品的表,以显示实际值与预测值之间的差的绝对值,如下所示:
Product | M1 difference | M2 difference | M3 difference
A 2 2 3
B 2 1 4
这是一个简单的查询还是需要创建一个新表?
答案 0 :(得分:1)
这里有一个使用自我join
和abs
的选项:
select t1.product,
abs(t1.forecastm1 - t2.forecastm1) as m1difference,
abs(t1.forecastm2 - t2.forecastm2) as m2difference,
abs(t1.forecastm3 - t2.forecastm3) as m3difference
from prediction t1
join prediction t2 on t1.product = t2.product
where t1.data = 'Actual'
and t2.data = 'Forecast'
答案 1 :(得分:0)
您可以使用如下查询:
SELECT act.Product
, act.M1 - forc.M1 AS M1Diff
, act.M2 - forc.M2 AS M2Diff
, act.M3 - forc.M3 AS M3Diff
FROM #notnormal AS act
INNER JOIN #notnormal AS forc ON forc.Product = act.Product
AND act.Data = 'Actual'
AND forc.Data = 'Forecast';
这是我设置用来显示它的模式:
CREATE TABLE #notnormal
(
Data VARCHAR(10)
, Product CHAR(1)
, M1 SMALLINT
, M2 SMALLINT
, M3 SMALLINT
);
INSERT INTO #notnormal
(
Data
, Product
, M1
, M2
, M3
)
VALUES
('Actual', 'A', 13, 16, 18)
, ('Actual', 'B', 22, 24, 30)
, ('Forecast', 'A', 15, 14, 21)
, ('Forecast', 'B', 24, 25, 26);