2016-08-13 56 views
0

我想確定我目前的設計是否最有意義。我有一個定價表,它總是有一個給定產品的默認值(ProductId)。根據多種環境,價格可能會被覆蓋。數據庫設計 - 覆蓋值

對於這個表:

table & data

我想獲得基於給定的市,縣,州或默認情況下,適當的價格。由於Type和Priority代表了相同的事情,並且可能僅限於int和索引(不需要字符串),所以這有點做作。我使用INT,因爲它允許我排序並優先選擇從內部查詢的TOP中選擇哪一個。使用這個SQL:

SELECT DISTINCT ProductId, prices.Price 
FROM [CCC].[Prices] p CROSS APPLY 
(
    SELECT TOP 1 Price 
    FROM [CCC].[Prices] p2 
    WHERE p.ProductId = p2.ProductId 
    AND (Type = 'Default' 
     OR (Type = 'City' AND TypeId = 553) 
     OR (Type = 'State' AND TypeId = '4')) 
    ORDER BY [Priority] DESC 
) prices 

獲取我正是我要尋找:

enter image description here


這兩種方法我正在考慮是:

所有的應用程序代碼(具有所有可用值,然後基於空值找到最合適的價格。

在SQL(上面已演示)中,採用desc 中按優先級排序的最高值並在SQL中使用交叉應用來獲取所有價格(與單個記錄相比)。合併(解決發佈的答案)也是一種解決方案,但過去我發現合併可能會很廣泛。我更喜歡這個版本。

我應該考慮其他方法或模式嗎?

+0

編輯您的問題並提供樣本數據和期望的結果。 –

回答

0

如果您打算使用cross apply,您可以在SQL Server中完成這項工作。像這樣的一種方法:

select t.*, p.price 
from t cross join 
    (select 
     from pricing p 
     where p.productid = t.productid and 
      (p.city = t.city or 
      p.county = t.county and p.city is null or 
      p.state = t.state and p.county is null and t.county is null or 
      p.state is null 
      ) 
     order by (case when p.city is not null then 1 
        when p.county is not null then 2 
        when p.state is not null then 3 
        else 4 
       end) 
    ) p 
0

如果圖案市,縣,州,默認是修復,你cuold通過外部連接做,合併,這樣的事情:

select t.*, coalesce(city.price, county.price, state.price, defaulttab.price) as price 
from t left outer join citytab as city t.productid = city.productid 
              and on t.city = city.city 
     left outer join countytab as county on t.productid = county.productid 
              and t.county = county.county 
     left outer join statetab as state on t.productid = state.productid 
              and t.state = state.state 
     join defautlttab on t.productid = defaulttab.productid 
+0

我考慮過這個版本,並會對它進行測試,但我認爲交叉應用在我的經驗中表現更好。我需要一個更大的測試桌來確定。 –