Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Trouble using a tariff table with banded pricing units to calculate a total price

$
0
0

I have the task of replicating a pricing model in SQL so that I can do some analysis on theoretical changes to tariffs. The tariffs I am working with are to do with distances travelled, and the price per distance unit varies at different break points in the journey. I need a function which will apply the tariff to a variable distance value, which is proving to be a real challenge. Once I have this set up I will need to be able to run for up to 3 million journeys at a time so I will need something pretty speedy.

I am using SQL Server 2012 with SSMS

Here is the CREATE script for the tariff table:

 
CREATE TABLE [dbo].[tariff_ratebrek](
	[break_seq_num] [int] NULL,
	[break_amount] [float] NULL,
	[break_unit] [float] NULL,
	[break_point] [float] NULL
) 

And here are some made-up sample values to enter:

INSERT INTO tariff_ratebrek_test
VALUES (0,400,0,0),
(1,100,0,2),
(2,200,1,3),
(3,150,1,5),
(4,250,1,6),
(5,400,1,7),
(6,250,1,10),
(7,220,1,28),
(8,200,1,55),
(9,150,1,99999)

The resulting table should look like this:

break_seq_num break_amount break_unit break_point
0 400 0 0
1 100 0 2
2 200 1 3
3 150 1 5
4 250 1 6
5 400 1 7
6 250 1 10
7 220 1 28
8 200 1 55
9 150 1 99999

So, the code I need should allow me to take an integer value representing distance and work out what the total price of the journey is, with these rules:

  • break_amount is the price per break_unit for distance travelled within each band
  • The start point of each band = break_point of the previous band + 1 (when ordered by break_seq_num)
  • The end point of each band = break_point
  • Where break_point = 0 the break_amount is included in the total price before any distance is travelled
  • Where break_unit = 0 the break_amount is the total price for the band
  • Otherwise, break_unit determines the units of distance at which the price increases by the break_amount

So for example, if a journey travelled a total distance of 12, the calculation would be:

0 miles travelled = 400

+ 0-2 miles @ 100 all-in = 500

+ 3rd mile @ 200/mile = 700

+ 4-5 miles @ 150/mile = 1000

+ 6th mile @ 250/mile = 1250

+ 7th mile @ 400/mile = 1650

+ 8-10 miles @ 250/mile = 2400

+ 11-12 miles @ 220/miles = 2840

If anyone knows a clever way of doing this please let me know as I am struggling and this would really unlock some amazing analytics opportunities

Thanks

Jack


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>