SQL AVG与案例

时间:2015-12-01 10:45:21

标签: sql case average

我有一个DB,它存储从C到AAA的值,而C是最差的,AAA是最好的。

现在我需要这个值的平均值,我不知道如何首先将值转换为int,计算平均值,将平均值四舍五入为int并将其转换回来。

说明:

C = 1
B = 2
A = 3
AA = 4
AAA = 5

使用SQL语句甚至可以实现吗?我试图将AVG和CASE结合起来,但我没有把它带到工作...... 谢谢你的帮助!

此致

2 个答案:

答案 0 :(得分:2)

select avg(case score 
             when 'C' then 1 
             when 'B' then 2
             when 'A' then 3
             when 'AA' then 4
             when 'AAA' then 5 
           end) as avg_score
from the_table;

(这假设该列被称为score

要将其转换回"字符值",请在另一种情况下包装输出:

select case cast(avg_score as int)
         when 1 then 'C'
         when 2 then 'B'
         when 3 then 'A'
         when 4 then 'AA'
         when 5 then 'AAA'
       end as avg_score_value
from (
    select avg(case score 
                 when 'C' then 1 
                 when 'B' then 2
                 when 'A' then 3
                 when 'AA' then 4
                 when 'AAA' then 5 
               end) as avg_score
    from the_table;
) t

以上cast(avg_score as int)假设ANSI SQL。您的DBMS可能有不同的方法将值转换为整数。

答案 1 :(得分:0)

我为你创造了这个例子。 你可以将你的排名投射到临时表中,然后计算,当你完成时,放弃它。

create table sof (id int identity,a nvarchar (10)) 
insert into sof values ('a')
insert into sof values ('b')
insert into sof values ('c')
select case a when 'AAA ' then 5
             when 'AA' then 4
             when 'A' then 3
             when 'B' then 2
             else 1
      end as av
into #temp
from sof
----for rounded
select ROUND(AVG(CAST(av AS FLOAT)), 4)
from #temp
--not rounded
select AVG (av)
from #temp