表:UnitsSold 列:
示例数据如下所示:
UnitsSold
ProductID Quantity Date ForecastOrActual
Widget 100 1-June-2015 F
Widget 120 1-June-2015 A
Gizmo 90 1-June-2015 F
Gizmo 80 1-June-2015 A
Doohickey 200 1-June-2015 A
我正在寻找一个sql查询,该查询返回一个聚合度量标准,指示实际值在给定周内的预测值。也是任何假设
感谢您的支持。感谢
答案 0 :(得分:0)
WITH
cte_A AS
( SELECT qty,product, DATEPART( wk, DATE) AS WEEK
WHERE FORCAST='A'
GROUP BY product,DATEPART( wk, DATE))
, cte_F AS
( SELECT qty,product, DATEPART( wk, DATE) AS WEEK
WHERE FORCAST='F'
GROUP BY product,DATEPART( wk, DATE))
SELECT cte_A.product,cte_A.week,
CASE
WHEN cte_F.qty - cte_A.qty >0 THEN 'Not met forcast'
WHEN cte_F.qty - cte_A.qty <0 THEN 'Met forcast'
END AS result
FROM cte_A join cte_F
ON cte_A.product=cte_F.product
AND cte_A.week=cte_F.week
如果您向我提供更多信息,我可以为您提供更好的代码。
DATEPART功能将为您提供当天的一周中的任意一天的数量,如果您的数据跨越多年,您可以使用该数字。 希望这会有所帮助。
根据您的评论进行更新:
为了获得更好的逻辑(-100到100)性能,您可以将其更改为:
WITH
cte_A AS
( SELECT qty,product, DATEPART( wk, DATE) AS WEEK
WHERE FORCAST='A'
GROUP BY product,DATEPART( wk, DATE))
, cte_F AS
( SELECT qty,product, DATEPART( wk, DATE) AS WEEK
WHERE FORCAST='F'
GROUP BY product,DATEPART( wk, DATE))
SELECT cte_A.product,cte_A.week,
CASE WHEN cte_F.qty = cte_A.qty THEN 0
ELSE 100.0*(cte_A.qty - cte_F.qty) / cte_F.qty As Performance
FROM cte_A join cte_F
ON cte_A.product=cte_F.product
AND cte_A.week=cte_F.week