2012-10-18 69 views
1

我需要創建一個報告,用戶可以切換數據從區域>區>委員會>事件。我使用我無法更改的設置數據視圖。我需要定義一個區域和一個區域,因爲它們在數據庫中沒有正確定義,然後將它們相互關聯。我已經接近,因爲我能夠分配17個不同的「DistrictCodes」 - 是啊,他們有代碼,但使用CASE語句時,沒有正確的調查侷限於彌補地區:在SSMS中結合案例陳述

CASE WHEN DistrictCode LIKE 'DST10%' THEN 4 
WHEN DistrictCode LIKE 'DST13%' THEN 2 
WHEN DistrictCode LIKE 'DST1%' THEN 2 
WHEN DistrictCode LIKE 'DST2%' THEN 2 
WHEN DistrictCode LIKE 'DST3%' THEN 3 
WHEN DistrictCode LIKE 'DST5%' THEN 3 
WHEN DistrictCode LIKE 'DST7%' THEN 2 
WHEN DistrictCode LIKE 'DST8%' THEN 1 
WHEN DistrictCode LIKE 'DSTC4%' THEN 3 
WHEN DistrictCode LIKE 'DSTC6%' THEN 2 
WHEN DistrictCode LIKE 'DSTC9%' THEN 1 
WHEN DistrictCode LIKE 'DT11%' THEN 4 
WHEN DistrictCode LIKE 'DT12%' THEN 4 
WHEN DistrictCode LIKE 'DT15%' THEN 4 
WHEN DistrictCode LIKE 'DT16%' THEN 4 
WHEN DistrictCode LIKE 'DT17%' THEN 4 
WHEN DistrictCode LIKE 'UP17%' THEN 4 
WHEN DistrictCode LIKE 'UPL11%' THEN 4 
ELSE 5 
END AS Region 

使用「區描述」數據我可以創建區:

CASE WHEN DistrictDesc IN ('1' , '1A' , '1B') THEN 'District 1' 
    WHEN DistrictDesc IN ('2' , '2A' , '2B' , '2C') THEN 'District 2' 
    WHEN DistrictDesc IN ('3' , '3A' , '3B') THEN 'District 3' 
    WHEN DistrictDesc IN ('4' , '4A' , '4B' , '4C' , '4D' , '4E' , '4F') THEN 'District 4' 
    WHEN DistrictDesc IN ('5' , '5A' , '5B' , '5C') THEN 'District 5' 
    WHEN DistrictDesc IN ('6' , '6A') THEN 'District 6' 
    WHEN DistrictDesc IN ('7' , '7A' , '7B') THEN 'District 7' 
    WHEN DistrictDesc IN ('8' , '8A' , '8B' , '8C') THEN 'District 8' 
    WHEN DistrictDesc IN ('9' , '9A') THEN 'District 9' 
    WHEN DistrictDesc IN ('10' , '10A' , '10B' , '10C') THEN 'District 10' 
    WHEN DistrictDesc IN ('11' , '11A' , '11B' , '11C') THEN 'District 11' 
    WHEN DistrictDesc IN ('12' , '12A' , '12B' , '12C') THEN 'District 12' 
    WHEN DistrictDesc IN ('13' , '13A') THEN 'District 13' 
    WHEN DistrictDesc IN ('14' , '14A' , '14B' , '14C' , '14D') THEN 'District 14' 
    WHEN DistrictDesc IN ('15' , '15A' , '15B' , '15C' , '15D') THEN 'District 15' 
    WHEN DistrictDesc IN ('16' , '16A' , '16B' , '16C') THEN 'District 16' 
    WHEN DistrictDesc IN ('17' , '17A' , '17B') THEN 'District 17' 
    ELSE ISNULL (DistrictDesc,'No District') 
    END AS District 

這返回的查詢工作在SSMS,但是當我預覽VS報表生成器的報告中,我需要設置區域作爲報告的參數。無論我是爲區域設置值還是從查詢中檢索值,我都會在區域的預覽中獲得1,2,3,4和5(我的區域)的倍數。

我怎樣才能得到它只返回一次1,2,3,4或5?有沒有一種方法可以將這些結合起來。如果我使用Distinct,那麼我會錯過一些不是我的數據?我已經嘗試使用IN並列出每個區碼,但返回了相同的問題。

回答

0

上面的代碼是不可維護的。

您應該創建一個分區表,將您的代碼和說明映射到並加入到該表中,並將其用作參數的來源。這將有解決您的問題的雙重好處,並改善您的查詢

+0

你的權利!我重寫了這個查詢,並且在我重寫時忽略了它的正確嵌套。謝謝! – user1729778