我正在尝试获得一个正在运行的演绎总数,但是当我有一个零行时会出现问题。我正在使用SQL Server 2012。
这是我当前的一批结果。
SuppressionDescription SuppressionPriority SuppressionPriorityOrder TotalRecords RecordsLost RunningTotal
Deceased_Bln 1 1 1376 2 1374
Pivotal Postcode Exclusions 9 2 1376 0 1374
Pivotal 3 Month Decline 11 3 1376 24 1352
Postcode exclusions (Complaints) 12 4 1376 0 1352
Gone Away (from Barcode on returned mail) 15 5 1376 30 1346
Pivotal prospects with a Do Not Mail flag 16 6 1376 234 1112
Email Suppression File 17 7 1376 7 1135
Opt outs & undeliverables from SMS system 18 8 1376 7 1362
Generic Phone Number Suppression 19 9 1376 245 1124
Exclude if not MR, MRS, MISS, MS, NULL 23 10 1376 0 1131
Total Prospects 9999 11 1376 0 1376
使用我的查询,前两行计算。共有1,376个减少2个叶子1,374,第二行没有RecordsLost,因此RunningTotal保持不变。到目前为止一切都很好。
但是因为第2行的计数为0,所以第3行(虽然它的RecordsLost为24)不同步。
我尝试添加各种case语句,尝试获取不同场景的总数,但它从来都不行。
以下是我的发言:
;WITH CTE AS (SELECT ID, SuppressionTypeID, ContactMethodType, SupplierName, SuppressionDescription
, SuppressionCount, TotalRecords, RecordsLost, SuppressionPriority, SuppressionPriorityOrder
, CASE WHEN SuppressionPriority = 9999
THEN TotalRecords
ELSE TotalRecords - RecordsLost END AS RowDiff
, CASE WHEN RecordsLost = 0
THEN LAG(RecordsLost, 1) OVER (PARTITION BY SupplierName, ContactMethodType ORDER BY SuppressionPriorityOrder)
ELSE RecordsLost END AS RecordsLostRoll
FROM #tmpSup
WHERE SupplierName = 'Freeman Grattan Holdings'
AND ContactMethodType = 'A'
)
SELECT SuppressionTypeID, ContactMethodType, SupplierName, SuppressionDescription
, SuppressionPriority, SuppressionPriorityOrder
, TotalRecords
, RecordsLost
, CASE WHEN SuppressionPriorityOrder = 1
THEN RowDiff
ELSE (LAG(RowDiff, 1, RowDiff)
OVER (PARTITION BY SupplierName, ContactMethodType ORDER BY SuppressionPriorityOrder)) - RecordsLost
END AS RunningTotal
FROM CTE
ORDER BY SupplierName
, ContactMethodType
, SuppressionPriority
我想将RunningTotal看作: 1374 1374 1350 1350 1320 1086 1079 1072 827 827 1376(总前景)
任何建议和提前感谢。