Skip to content
Advertisement

How to calculate table values dynamically and find Min and Max target from parameter in SQL Server

I want to calculate table values dynamically and find Min and Max target from parameter

I have the following target table with data:

I am passing a parameter AchievedTarget for a particular quarter (1, 2, 3, 4).

IF quarter = 1 and AchievedTarget = 250000 I want the record where AchievedTarget lies in between

Output should be like:

enter image description here

IF quarter = 1 and AchievedTarget = 400000 I want the record where AchievedTarget lies in between

Output should be like:

enter image description here

IF quarter = 2 and AchievedTarget = 400000, I want to sum GivenTarget column from Target tables where Quarter = 1, Method = ’AB’, Method_ID = 1 With Quarter= 2 Method = ’AB’ Method_ID = 1 and so on for add each respective method and Method_ID with quarters, and need to pick Percentage values from current Quarter i.e Quarter 2 in this case with respective Method and Method_ID

Expected New Target tables for Quarter 2 should be as follows:

enter image description here

Now depend upon above table I want to calculate Min_Target and Max_Target as calculated earlier

Expected output with Quarter= 2 and AchievedTarget= 500000 should be:

enter image description here

Following is the code which i was trying, its gives me output for Quarter = 1 only

I am not able to calculate table values dynamically and find Min and Max target from parameter quarter.

Advertisement

Answer

I have put together a set of sample data and query that will do this. I have removed references to Mothod, as you only have 1 row per Mothod per quarter. You can add the column back in to my solution if you have more rows that your sample.

First set up the table and test data

Add a top row in case as a catch for anyone who has achieved higher than your top target

Set up your conditions. I have taken out Mothod as you only have one row per Mothos per Qtr

Use a CTE to get cumulative totals per qtr, and a second CTE to flatten each row so it also had the values of the previous row. I’ve used row_number to make sure I correctly order your rows, even though in your sample date mothod_id appears to also have the same data.

The final query then simply finds the correct row out of the CTE.

Result, using @qtr=2 and @achieved=500000:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement