我有一个sql,如下:
select case when  ((A.a-B.b)/A.a)<0.2 then 0 when ((A.a-B.b)/A.a)<0.5 then 0.5 else 1 end as aa
from A,B
where A.id=b.id
请问这个语句可以简化吗?
A,B是表,a,b,id是字段。

解决方案 »

  1.   

    可以有另外一种思路:select case when ((A.a-B.b)/A.a)>=0.5 then 1 else convert(decimal(6,1),convert(int,((A.a-b.b)/A.a*2))/2 end as aa
    from A,B
      

  2.   

    create function dbo.fn_level 
    ( @a1 float, @a2 float ) 
    returns int as
    begin
        declare @n = float
        set @n = (@a1 - @a2) / @a1
        if @n < .2 return 0
        if @n < .5 return .5
        return 1
    end
    go
    select dbo.fn_level(A.a, B.b) from A, B where A.id = B.id
      

  3.   

    这样算简化吗,呵呵,只是参与一下
    select  case when (1-B.b/A.a)<0.2 then 0 when (1-B.b/A.a)<0.5 then 0.5 else 1 end as aa
    from A,B
    where A.id=b.id
    如果能保证 b字段在A表中没有 ,a字段在B表中没有,下面写的可以写的更少些,
    select  case when (1-b/a)<0.2 then 0 when (1-b/a)<0.5 then 0.5 else 1 end as aa
    from A,B
    where A.id=b.id
    只是 参与 本质没变。
      

  4.   

    因为你的条件是大于,小于,因此无法使用case ((A.a-B.b)/A.a) when <0.2 then 0 when <0.5 else 1 end
    无法简化了!