I am trying to do a calculation based on a lookup table doing a cross join and I am trying to select just 1 record per ID. This is on a SQL Server 2019 server.
I want 1 record from the TechFee table and the TechFee from the TechFeeTiers table where the projected spend is equal or greater than the target spend.
select
tf.[BrandSupplierTechFeeId],
tf.[BuyerContactId],
tf.[ReviewCompleted],
tf.[BrandSupplierId],
tf.[PriorYearSpend],
tf.[CurrentYearSpend],
tf.[ProjectedSpend],
CASE WHEN tf.[ProjectedSpend] >=tft.TargetSpend and tft.Tier = 'Tier 1' THEN tft.TechFee
WHEN tf.[ProjectedSpend] >=tft.TargetSpend and tft.Tier = 'Tier 2' THEN tft.TechFee
WHEN tf.[ProjectedSpend] >=tft.TargetSpend and tft.Tier = 'Tier 2' THEN tft.TechFee
WHEN tf.[ProjectedSpend] >=tft.TargetSpend and tft.Tier = 'Tier 3' THEN tft.TechFee
WHEN tf.[ProjectedSpend] >=tft.TargetSpend and tft.Tier = 'Tier 4' THEN tft.TechFee
WHEN tf.[ProjectedSpend] >=tft.TargetSpend and tft.Tier = 'Tier 5' THEN tft.TechFee
WHEN tf.[ProjectedSpend] >=tft.TargetSpend and tft.Tier = 'Tier 6' THEN tft.TechFee
ELSE NULL END CurrTechFee,
tf.[PriorYearTechFee]
FROM TechFees tf, TechFeeTiers tft
order by tf.[BrandSupplierTechFeeId],CurrTechFee desc
Expected output is one row per ID with the the projected spend closest to the TargetSpend.
| ID | ProjectedSpend | CurrTechFee |
|----|----------------|-------------|
| 1 | 4362452 | 7500 |
| 2 | 1630481.875 | 3500 |
| 3 | 17795582 | 10000 |
| 4 | 1010422.625 | 3500 |
| 5 | 16245146 | 10000 |
| 6 | 4430861 | 7500 |
| 7 | 1650944.625 | 3500 |
| 8 | 80948944 | 30000 |
| 9 | 336441216 | 50000 |
| 10 | 4396726.5 | 7500 |
My tables and query attempt are below in the SQL Fiddle link. Any help or guidance is much appreciated.