SQL - 浓缩重复的布尔'THEN'语句

时间:2012-07-30 14:35:45

标签: sql-server-2005

请任何人都可以建议一种方法来压缩这些代码,以减少其重复性。非常感谢

    select case
    when c=1 and cs=1 and f=0 and fs=0 then 'FPL02'
    when c=0 and cs=0 and f=1 and fs=1 then 'FPL03'
    when c=1 and cs=0 and f=0 and fs=0 then 'FPL04'
    when c=0 and cs=0 and f=1 and fs=0 then 'FPL05'
    when c=1 and cs=1 and f=1 and fs=1 then 'FPL06'
    when c=1 and cs=1 and f=1 and fs=0 then 'FPL07'
    when c=1 and cs=0 and f=1 and fs=1 then 'FPL08'
    when c=1 and cs=0 and f=1 and fs=0 then 'FPL09'
    when Ab=1 then 'FPL10'
    when cpc=1 and plo=0 then 'FPC01'
    when cpc=0 and plo=1 then 'FPC02'
    when cpc=1 and plo=1 then 'FPC03'
    else 'FPL01' end

    from (select ptmatter, BillLHAbsolute as Ab, BillLHChildren as C, BillLHChildrenSettle as CS, BillLHFinances as F, BillLHFinancesSettle as FS, BillLHCPC as CPC, BillLHPLO as PLO from MatterDataDef) as mmd
    where ptmatter=$matter$

1 个答案:

答案 0 :(得分:2)

在不同的列上有许多不同的条件语句,我真诚地怀疑你可以压缩那些代码,同时还能让其他人维护它。

例如,你需要这个:

select case
    when c IN (0, 1) AND cs IN (0, 1) AND f IN (0, 1) AND fs IN (0, 1) then
        case     
            when c=1 and cs=1 and f=1 and fs=0 then 'FPL07'     
            when c=1 and cs=0 and f=1 and fs=0 then 'FPL09'     
            else 'FPL0' + cast(c * 5 + f * 6 - cs * 2 - fs * 2 - 1 as char(1))
        end
    when Ab = 1 then 
        'FPL10'
    when cpc IN (0, 1) AND plo IN (0, 1) then
        'FPC0' + cast(cpc * 1 + plo * 2 as char(1))
    else 
        'FPL01' 
    end

它是浓缩的(某种程度上的),但由于可读性较低,你的线路较少。

总而言之,真的不是那么多WHEN陈述。