使用CASE和WHERE语句和计数器SQL

时间:2013-08-29 11:32:01

标签: sql sql-server

我想做查询。我使用的是Microsoft SQL。

  • 如果产品等于FAST ......
    • 和tree_level等于0,1,2,3,4,5,然后计算0,1,2,3,4,5的数量。例如,如果有30个项目的数量包含“0,1,2,3,4,5”。然后乘以30 * 2.
    • 和tree_level等于-1,然后计数-1并乘以2
  • 如果product等于MOBIL且tree_level等于0,1,2,3,4,5,则计算该数字并乘以3
  • 如果产品等于FACE ......
    • 和tree_level等于0,1,2,3,4,5,然后计算0,1,2,3,4,5的数量并乘以3
    • 和tree_level等于-1,然后计数-1并乘以2

如何将where,case和counter语句一起使用?我做不到。

select
    DS.PersTel ,
    DW.AD ,
    DW.SOYAD ,
    DS.RefPhoner   ,
    DS.Product ,
    DS.Tree_level 

WHERE DS.Product like '%FACE%' (
CASE  
WHEN DS.Tree_level IN (0,1,2,3,4,5) THEN count(DS.Tree_level) * 3 
WHEN DS.Tree_level IN (-1) THEN count(DS.Tree_level) * 2
END  

WHERE DS.Product like '%MOBIL%'  (
CASE DS.Tree_level
WHEN DS.Tree_level IN (0,1,2,3,4,5) THEN count(DS.Tree_level) * 3 
END  )

WHERE DS.Product like '%FAST%' (
CASE  DS.Tree_level
WHEN DS.Tree_level IN (0,1,2,3,4,5) THEN count(DS.Tree_level) * 2 
WHEN DS.Tree_level IN (-1) THEN count(DS.Tree_level) * 2
END  )


    from dw_prod.FRTN.DIG_SEFER  AS DS 
    inner join dw_prod.dbo.DW_MUST AS DW 
    ON DW.CEP_TEL = DS.PersTel

更新了案例部分

       select
        DS.PersTel ,
            DW.AD ,
            DW.SOYAD ,
            DS.RefPhoner   ,
            DS.Product ,
            DS.Tree_level 
    CASE  
    WHEN DS.Tree_level IN (0,1,2,3,4,5)AND DS.Product LIKE '%FACE%' THEN count(DS.Tree_level) * 3 
    WHEN DS.Tree_level IN (-1) THEN count(DS.Tree_level) * 2
    END AS Answer1 

    CASE DS.Tree_level
    WHEN DS.Tree_level IN (0,1,2,3,4,5) AND DS.Product LIKE '%MOBIL%' THEN count(DS.Tree_level) * 3 
    END AS Answer2 

    CASE  DS.Tree_level
    WHEN DS.Tree_level IN (0,1,2,3,4,5) AND DS.Product LIKE '%FAST%' THEN count(DS.Tree_level) * 2 
    WHEN DS.Tree_level IN (-1) THEN count(DS.Tree_level) * 2
    END AS Answer3

  from d.FR  AS Ds 
            inner join d.dbo.DW AS Dw 
            ON DW.CEP_TEL = DS.PersTel

1 个答案:

答案 0 :(得分:1)

这应该让你开始:

select
    product,
    tree_level,
    count(1) over (partition by product,tree_level_category) 
        * case when product like '%FACE%'
               then case tree_level_category
                        when '0-5' then 3
                        when '-1' then 2
                    end
               when product like '%MOBIL%'
               then case tree_level_category
                        when '0-5' then 3
                    end
               when product like '%FAST%'
               then case tree_level_category
                   when '0-5' then 2
                   when '-1' then 2
              end
        end 
from (
    select
        product,
        tree_level,
        case when tree_level in (0,1,2,3,4,5)
             then '0-5'
             when tree_level = '-1'
             then '-1'
             else null 
        end tree_level_category
    from
       product
) as t

SQLFiddle here