2010-03-01 62 views
2

我有一個稅率表,其中NULL實體類型行表示默認稅率。根據行中的字段值合併行

Year End | EntityType | RateType | TaxRate 
------------------------------------------ 
2009 |  NULL | Interest |  13 
2009 |  NULL | Other |  8 
2009 |  NULL | Interest |  13 
2010 |  NULL | Other |  9 
2009 | Company | Interest |  15 
2010 | Individual | Other |  6 

我想創建一個Entitytype作爲參數的表的存儲過程。例如,如果它存在,它將返回該實體類型的稅率,否則返回該年的NULL行和ratetype。

即:查詢上面的EntityType個人應返回

Year End | EntityType | RateType | TaxRate 
------------------------------------------ 
2009  |  NULL | Interest |  13 
2009  |  NULL | Other |  8 
2009  |  NULL | Interest |  13 
2010  | Individual | Other |  6 

任何人可以提出一個方法,我可以做到這一點?

由於提前,

回答

2
SELECT 
    t1.year_end, 
    t1.entity_type, 
    t1.ratetype, 
    COALESCE(t2.taxrate, t1.taxrate) 
    FROM 
    Rates AS t1 
LEFT JOIN 
    Rates AS t2 ON 
     t1.year_end = t2.year_end 
     AND t2.entitytype IS NULL 
WHERE t1.year_end = @year 
    AND t1.entitytype = @entitytype