我设法从数据库中获取数据,如下所示:
STOCKNAME | STORENAME | WEEKNUM | SOH | SALES
Apples | Store 1 | 10 | 1 | 3
Apples | Store 1 | 9 | 4 | 1
Apples | Store 1 | 8 | 5 |
Pears | Store 1 | 10 | 15 | 0
Pears | Store 1 | 9 | 15 | 0
Pears | Store 1 | 8 | 15 |
Mangoes | Store 1 | 10 | 33 | 15 <-- They could have received more stock between week week
Mangoes | Store 1 | 9 | 25 | 8
Mangoes | Store 1 | 8 | 32 |
Weeknumber会根据导入下一组信息的时间而变化,例如。下周将是第11周,每家商店将通过他们的库存(SOH)发送。然后几周将变为11,10,9。
我想知道是否有一种简单的方法来计算周数之间的差异,而没有先计算第10周和第9周之间的差异(CALC A)。然后计算第9周和第8周之间的差异。然后计算(CALC B)之间的差异。然后计算(CALC A) - (CALC B)
之间的差异预期成果
STOCKNAME | STORENAME | SALES | SOH
Apples | Store 1 | 4 | 1
Pears | Store 1 | 0 | 15 **<--- Alert Stock Not Selling. Attention Require!!**
Mangoes | Store 1 | 23 | 33
报告的目的是确保过去3周内库存有变动。
所以那里的苹果一直在流动。 梨子有问题。
到目前为止,这是我的思路:
我认为这可能是一个答案。可能不是最好的。
在没有周数的情况下添加Sales / SUM From Data。这应该显示过去三周是否有任何单位销售。使用名为 TransactionType 的别名添加一个额外的静态列,其值为“Sales Last 3 Weeks”
SELECT STOCKNAME, STORENAME, 0 AS SOH, SUM(SALES) AS QTY, 'Sales Last 3 Weeks' AS TRANSACTIONTYPE
FROM TABLE1
GROUP BY STOCKNAME, STORENAME,'Sales Last 3 Weeks' AS TRANSACTIONTYPE
对数据运行另一个查询并显示MAX Weeknumber SOH数字。使用名为 TransactionType 的别名添加一个额外的静态列,其值为'Current SOH'
SELECT STOCKNAME, STORENAME, SOH, 0 AS QTY, 'SOH' AS TRANSACTIONTYPE
FROM TABLE1
GROUP BY STOCKNAME, STORENAME,'SOH' AS TRANSACTIONTYPE
HAVING WEEKNUMBER = 10 <-- Not sure how to dynamic this. Weeknumber will change
UNION上面的查询1和2.
SELECT * FROM QUERY1
UNION
SELECT * FROM QUERY2
然后搜索这些结果
CASE WHEN (QTY = 0 and SOH > 0) THEN 'Attention Required Here' ELSE 'Everything is Cool' END