I'm trying to implement a price fallback system in SQL server. I'd like to have a set of increasingly specific prices (eg: by region, store, warehouse, etc.) for a product, that may or may not be defined, and be able to select the most specific prices (ie: the one with most parameters defined) in a report.
For example, I might have the following data:
Region
--------
1
2
Store
--------
1
2
3
Product | Region | Store | Price
--------------------------------
Foo | NULL | NULL | 1.0
Foo | 1 | NULL | 2.0
Foo | 1 | 1 | 2.5
Foo | 1 | 2 | 2.3
So if I wanted to know the price for product Foo...
- in Region 1, Store 1 = 2.5
- in Region 1, Store 3 = 2.0 (Store 3 is not defined explicitly in the data, so the result comes from the NULL store for Region 1)
- in Region 2, Store 4 = 1.0 (Region 2 is not defined explicitly in the data, so the result comes from the NULL region)
For the sake of simplicity, I can assume that the Store is always more specific than the region, and a store can only exist in one region.
A schema for this data would be something like this:
CREATE TABLE Prices(
ID int IDENTITY(1,1) NOT NULL,
Product int NOT NULL,
Region int NULL,
Store int NULL,
Price money NOT NULL,
CONSTRAINT PK_Prices PRIMARY KEY CLUSTERED (ID ASC),
CONSTRAINT IX_Prices UNIQUE NONCLUSTERED (Product ASC, Region ASC, Store ASC)
)
Aside from crunching this data in code, how can I query this table for a list of effective prices for every product, based on (Region, Store)?