2013-06-02 21 views
1

我有一個州和縣的法規條例表:如何完成的屬性列表是相同的父母的

RegID State County RegulationName Regulation 
    1  CA    weight   10 pounds  
    1  CA    distance  20 miles 
    2  CA  Orange distance  22 miles 

父(州)全州有法規,恩。重量和距離。

孩子們(縣)可能會覆蓋一些規定。在這個例子中,奧蘭治縣用它自己的價值22英里覆蓋國家法規「距離」。

奧蘭治縣的「重量」法規未列在表中。因爲這意味着奧蘭治縣使用父母的「權重」

總是顯示縣級所有法規的完整列表的方式是什麼?返回縣級未覆蓋的隱含州級規定。 例如:

RegId State County RegulationName Regulation 
    1  CA    weight   10 pounds  
    1  CA    distance  20 miles 
    2  CA  Orange weight   10 pounds 
    2  CA  Orange distance  22 miles 
+0

當一個值是由多個局部調節取代,是獲勝價值總是最低還是最高,或者只是更本地? – HABO

+0

更多本地獲勝 – ob213

回答

1

假設它是縣規定簡單的情況下取代國家規定不論所涉及的值:

declare @Regulations as Table (RegulationId Int Identity, RegId Int, State VarChar(2), 
    County VarChar(16), RegulationName VarChar(16), Regulation VarChar(16)); 

insert into @Regulations (RegId, State, County, RegulationName, Regulation) values 
    (1, 'CA', NULL, 'weight', '10 pounds'), 
    (1, 'CA', NULL, 'distance', '20 miles'), 
    (2, 'CA', 'Orange', 'distance', '22 miles'), 
    (3, 'NY', NULL, 'weight', '1 stone'), 
    (4, 'NY', 'NYC', 'weight', '16 grams'), 
    (5, 'ND', NULL, 'shoe size', '9E'); 

select * from @Regulations; 

-- Start with all of the explicitly stated regulations. 
select RegId, State, County, RegulationName, Regulation, 'Explicit' as [Type] 
    from @Regulations 
union all 
-- Then add all of the missing county level regulations. 
select L.RegId, L.State, C.County, L.RegulationName, L.Regulation, 'Implicit' 
    from @Regulations as L cross join 
    (select distinct County, State from @Regulations where County is not NULL) as C left outer join 
    @Regulations as R on R.State = L.State and R.County = C.County and R.RegulationName = L.RegulationName 
    -- Where the regulation applies at the state level (L.County is NULL) and 
    -- there is no matching county level row (R.County is NULL from the LEFT OUTER JOIN). 
    where L.County is NULL and R.County is NULL and C.State = L.State 
    order by State, County, RegulationName; 
相關問題