Question

Essentially I have a test case scenario where I need to assign calculated percentages to a text value. E.g. < 80 = 'B' < 70 = 'C'

Here is the relevant portion of my code that pulls the value into a percent based on number of assignments handed in.

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

I have tried wrapping this with a case such as

Case when (100 * COUNT(CASE TurnedIn WHEN 1 THEN 1 ELSE NULL END) 
                             / COUNT(TurnedIn)) <= 80  Then 'B' As LetterGrade 

but no luck so far.

Was it helpful?

Solution 2

Write as:

    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

OTHER TIPS

You can try this,

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top