sql 语句如何按两个字段的计算结果排序

2024-12-18 21:23:20
推荐回答(4个)
回答1:

1、a和b都不为空值或null值,分母也无0值
select a/b as c,a,b from table order by a/b

2、a或b其中一个为null值是,将null值转换为1且分母也无0值:
select isnull(a,1)/isnull(b,1) as c,a,b from table order by isnull(a,1)/isnull(b,1)

3、a或b其中一个为null值是,将null值变为非null值的那一列的值且分母也无0值:
select NULLIF(COALESCE(a,b), 0.00)/NULLIF(COALESCE(b,a), 0.00) as c,a,b from table order by NULLIF(COALESCE(a,b), 0.00)/NULLIF(COALESCE(b,a), 0.00) as c

4、a和b不为空也不为null 但是分母为0时:
select round(a/nullif(b,0),2) as c,a,b from table order by round(a/nullif(b,0),2) as c

回答2:

直接select * from tabe order by A/B就行,但是你得判断A/B这个表达式的正确定
这两个字段得是数字型的,而且B不能是0

回答3:

select t.a,t.b from (select a/b as c,a,b from 表)t order by t.c

回答4:

select a,b,a/b from tab order by a/b