To the table I need to calculate DISCOUNT_AMOUNT
and AMOUNT_REST
as follows in the formula view. For every NAME
there is a unique amount repeated in every row, but the discount isnt AMOUNT*DISCOUNT%
in all rows, only the first discount order by ascending DATE
. The next discounts for the same NAME
are applied to the AMOUNT_REST
.
A way to solve this in SQL Server language?
select [NAME], [AMOUNT], [DISCOUNT%], [DATE]--, DISCOUNT_AMOUNT, AMOUNT_REST
FROM [Table]
order by [NAME], [DATE] asc
This is what a I want:
[NAME] | [AMOUNT] | [DATE] (dd-MM-yyyy) | [DISCOUNT%] | [DISCOUNT_AMOUNT] | [AMOUNT_REST] |
---|---|---|---|---|---|
Peter | $100 | 01-01-2023 | 4% | $4,0 | $96,0 |
Peter | $100 | 02-01-2023 | 20% | $19,2 | $76,8 |
Peter | $100 | 03-01-2023 | 5% | $3,8 | $73,0 |
John | $500 | 01-01-2023 | 40% | $200,0 | $300,0 |
John | $500 | 02-01-2023 | 3% | $9,0 | $291,0 |
Sara | $200 | 01-01-2023 | 9% | $18,0 | $182,0 |
Sara | $200 | 02-01-2023 | 10% | $18,2 | $163,8 |
This is the Excel-manual way to do it
[NAME] | [AMOUNT] | [DATE] (dd-MM-yyyy) | [DISCOUNT%] | [DISCOUNT_AMOUNT] | [AMOUNT_REST] |
---|---|---|---|---|---|
Peter | 100 | 44927 | 0,04 | B2*D2 | B2*(1-D2) |
Peter | 100 | 44928 | 0,2 | F2*D3 | F2*(1-D3) |
Peter | 100 | 44929 | 0,05 | F3*D4 | F3*(1-D4) |
John | 500 | 44927 | 0,4 | B5*D5 | B5*(1-D5) |
John | 500 | 44928 | 0,03 | F5*D6 | F5*(1-D6) |
Sara | 200 | 44927 | 0,09 | B7*D7 | B7*(1-D7) |
Sara | 200 | 44928 | 0,1 | F7*D8 | F7*(1-D8) |
2条答案
按热度按时间ar7v8xwq1#
Although there might be a mathematical approach to compute the cumulative discount using window functions, this seems more easily approached with a recursive query:
The first CTE,
data
, enumerates the rows of eachname
. Thenrcte
starts from the first row of each partition and iterates, basically applying the same computation logic as the Excel formulas in your question.hyrbngr72#
Math: log (a+b) = log(a) * log(n), so we can calculate exp(sum(log(col))
https://dbfiddle.uk/IZMXyxUq