您好:
如下語法
第2筆,有抓到上一筆的 值來累加
但第三筆 ,上一筆 未計算前是0
結果就 沒有累加到
請問,這有什麼方式解決?
謝謝
SELECT *,isnull( LAG(x.sum_k) OVER(PARTITION BY nox, x.LDATE ORDER BY rw ),0 ) 'A',
k+ isnull( LAG(x.sum_k) OVER(PARTITION BY nox, x.LDATE ORDER BY rw ),0 ) 'B',
case
When rw<8000 then sum_k
else sum(CASE WHEN rw<8000 THEN 0 else k end) OVER(PARTITION BY nox, x.LDATE ORDER BY rw)
end
FROM (
SELECT 'A001' 'nox', 8.0 'k',12 'sum_k', '1120901' 'LDATE', 10 'rw'
UNION ALL
SELECT 'A001' 'nox', 8.0 'k',20 'sum_k', '1120901' 'LDATE', 20 'rw'
UNION ALL
SELECT 'A001' 'nox', 8.0 'k',0 'sum_k', '1120901' 'LDATE', 8001 'rw'
UNION ALL
SELECT 'A001' 'nox', 8.0 'k',0 'sum_k', '1120901' 'LDATE', 9001 'rw'
UNION ALL
SELECT 'A001' 'nox', 8.0 'k',0 'sum_k', '1130901' 'LDATE', 9001 'rw'
) x
最後有用 來做;但不知是否有更好的方法?
case
When rw<8000 then sum_k
else sum(CASE WHEN rw<8000 THEN 0 else k end) OVER(PARTITION BY nox, x.LDATE ORDER BY rw) +
MAX(x.sum_k) OVER(PARTITION BY nox, x.LDATE ORDER BY rw )
累加的話,可以參考該官方範例 - D. 指定 ROWS 子句,直接用 sum 就可以做到才是
對,有SUM 累加,但因為RW <80002的累加在前面了,無法在累加
要區分開來(有SUM_K)的已經是前面累加的
範例內 ROWS UNBOUNDED PRECEDING 這段語法可以了解看看,你提供的 SUM 語法內並沒有使用到或是查 running total 這個關鍵字找些資料來看看
SELECT BusinessEntityID, TerritoryID
,CONVERT(VARCHAR(20),SalesYTD,1) AS SalesYTD
,DATEPART(yy,ModifiedDate) AS SalesYear
,CONVERT(VARCHAR(20),SUM(SalesYTD) OVER (PARTITION BY TerritoryID
ORDER BY DATEPART(yy,ModifiedDate)
ROWS UNBOUNDED PRECEDING),1) AS CumulativeTotal
FROM Sales.SalesPerson
WHERE TerritoryID IS NULL OR TerritoryID < 5;