如何在SQL视图中将字符串值分配给数值

时间:2014-04-08 09:20:52

标签: sql sql-server tsql case

基本上我有一个测试用例场景,我需要将计算的百分比分配给文本值。例如。 < 80 =' B' < 70 =' C'

以下是我的代码的相关部分,它根据提交的分配数量将值拉入百分比。

Select *...
    100 * COUNT(CASE TurnedIn WHEN 1 THEN 1 ELSE NULL END) 
                             / COUNT(TurnedIn) AS Percentage, 
From Table1
When ...

我尝试用

这样的案例包装它
Case when (100 * COUNT(CASE TurnedIn WHEN 1 THEN 1 ELSE NULL END) 
                             / COUNT(TurnedIn)) <= 80  Then 'B' As LetterGrade 

但到目前为止没有运气。

2 个答案:

答案 0 :(得分:3)

你可以试试这个,

With CTE as
(

Select (100 * COUNT(CASE TurnedIn WHEN 1 THEN 1 ELSE NULL END) 
                      / COUNT(TurnedIn))        as Percentage

  from myTable          
)           
select Case When Percentage <70 
            Then 'C' 
            When Percentage <80
            Then 'B' 
            Else 'A'
        End
 from CTE

答案 1 :(得分:2)

写为:

    Select *, --name all columns you want
           case when Percentage < 80 then 'B'
                when  Percentage < 70 then 'C'
                else 'Add the grade which should be default when above 2 
                      case conditions are not met'
           end as LetterGrade
    from (      
    Select *,
        100 * COUNT(CASE TurnedIn WHEN 1 THEN 1 ELSE NULL END) 
                                 / COUNT(TurnedIn) AS Percentage 
    From Table1
    When ..) T