SQL按日期条件计算两列累积求和的问题求助
Fixing the Cumulative Calculation in Your SQL Query
Let's break down what's wrong with your current approach and fix it to match your requirements.
Why Your Current Query Fails
Your existing SQL uses ID for ordering in the window function, which doesn't align with the date-based logic you need. The conditional CASE statement also doesn't correctly isolate the RecAmt values from records where RecDate is earlier than the current row's SubDate.
Correct Approach
For each record, we need to:
- Take the current row's
SubAmt - Add the sum of
RecAmtfrom all records in the sameClasswhereRecDateis earlier than the current row'sSubDate
We also need to handle date formatting inconsistencies (some dates use 2-digit years, others 4-digit) by converting them to proper date types for accurate comparison.
Corrected SQL Query
SELECT t1.ID, t1.Class, t1.SubDate, t1.RecDate, t1.SubAmt, t1.RecAmt, t1.SubAmt + COALESCE( (SELECT SUM(t2.RecAmt) FROM TableName t2 WHERE t2.Class = t1.Class AND CONVERT(date, t2.RecDate, 3) < CONVERT(date, t1.SubDate, 3)), 0 ) AS Cumulative FROM TableName t1 ORDER BY t1.Class, CONVERT(date, t1.SubDate, 3);
How This Works
- Date Conversion:
CONVERT(date, [DateColumn], 3)converts yourdd/mm/yyordd/mm/yyyystrings to valid date types, ensuring accurate chronological comparison. - Correlated Subquery: For each row
t1, the subquery finds all matchingClassrecords whereRecDateis earlier thant1.SubDate, sums theirRecAmt. - COALESCE: Handles cases where there are no matching earlier records (like ID 1) by replacing
NULLwith 0, so we just use the currentSubAmt. - Ordering: Results are sorted by
ClassandSubDateto make it easier to verify cumulative values.
Example Verification
- ID 1: No
RecDatevalues are earlier than23/08/15, soCumulative = 12710 + 0 = 12710✔️ - ID 3:
RecDatefrom ID 1 (15/10/2015) is earlier than23/10/15, soCumulative = 2096 + 10613 = 12710✔️ - ID 8:
RecDatevalues from ID 1 and ID 6 are earlier than23/03/16, soCumulative = 217168 + (10613 + 78416) = 306197✔️
内容的提问来源于stack exchange,提问作者Jane Doe
相关产品推荐
相关产品推荐

