2015-12-01 51 views
0

我有一个DB存储从C到AAA值,而C是最差和AAA最好的。SQL AVG与案例

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

定义:

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

是,即使可能有一个SQL语句?我试图将AVG和CASE结合起来,但我没有把它运行起来...... 感谢您的帮助!

问候,

+3

发布您到目前为止所尝试的内容。 –

+1

一次做一件事。首先将字母转换为相关的数字。 –

+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可能有不同的方法将值转换为整数。

+0

非常感谢!它的工作原理是:-) 但是Apache Derby围绕着这个值 - 例如 - 1.8到1 ...但是我想我找到了一个解决方案(用round和float);-) – Contoweb

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 
+0

什么是“ur排名”? –

+0

我认为这是一个排名专栏。 像AAA是最好的/更糟的。 – DnL

+0

那么,“你”是什么? –