Created
August 22, 2020 15:56
-
-
Save brovish/54921535f5d7a0a99d95c4e0e626e6bc to your computer and use it in GitHub Desktop.
Every fifth order entitles your customer to a discount. The amount of the discount is based upon the total amount of the four orders leading up to the fifth order.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- Listing 12-16: Creating a Temporary Table of Order Totals for a Customer | |
| SELECT IDENTITY(INT, 1, 1) AS Sequence, | |
| O.OrderID, | |
| SUM(OD.Quantity * OD.UnitPrice) AS Total | |
| INTO #Totals | |
| FROM Orders AS O | |
| JOIN [Order Details] AS OD | |
| ON OD.Orderid = o.OrderID | |
| WHERE O.CustomerID = 'SAVEA' | |
| GROUP BY | |
| O.OrderID | |
| ORDER BY | |
| O.OrderID | |
| CREATE UNIQUE CLUSTERED INDEX #Idx ON #Totals(Sequence) | |
| -- Listing 12-17: Calculating the Discount | |
| SELECT OrderID, | |
| Total, | |
| Previous4, | |
| CASE | |
| WHEN Previous4 < 10000.00 THEN 5 | |
| WHEN Previous4 BETWEEN 10000.00 AND 15000.00 THEN 10 | |
| ELSE 20 | |
| END AS Discount | |
| FROM ( | |
| SELECT T1.OrderID, | |
| T1.Total, T1.Sequence, | |
| ( | |
| SELECT SUM(T2.Total) AS Total | |
| FROM #Totals AS T2 | |
| WHERE T2.Sequence >= T1.Sequence - 4 | |
| AND T2.Sequence < T1.Sequence | |
| ) AS Previous4 | |
| FROM #Totals AS T1 | |
| WHERE 0 = T1.Sequence % 5 | |
| ) AS X |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment