让我们假设一个表格就像
Acc_nbr sal1 sal2 sal3 sal4
123 10 20 30 40
124 10 30 40 15
126 16 20 25 16
所以在上表中我想消除min&需要采取最大的sal列和剩余的sal列!
例如:对于acc_nbr 123分钟sal = 10&最大sal = 40 因此,根据我的要求,我需要消除10& 40,&需要只需要20和30。 与其他acc_nbr相同。 请帮助..提前感谢!
答案 0 :(得分:1)
由于各种原因,这是一个难题:
NULL
值可能非常麻烦。如果我假设这些值都不是NULL
并且您不介意在极端情况下存在重复项,那么以下内容将起作用:
select t.*,
(case when sal1 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
then sal1
when sal2 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
then sal2
when sal3 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
then sal3
when sal4 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
then sal4
end) as first_sal,
(case when sal4 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
then sal4
when sal3 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
then sal3
when sal2 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
then sal2
when sal1 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
then sal1
end) as second_sal
from t;
我应该注意到,这个问题在几乎任何其他数据库中都会更容易。
编辑:
Golly,您没有提到输出中需要多少列。如果我们只是NULL
了极值,那就更容易了:
select t.*,
(case when sal1 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
then sal1
end) as sal1,
(case when sal2 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
then sal1
end) as sal2,
(case when sal3 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
then sal1
end) as sal3,
(case when sal4 not in (least(sal1, sal2, sal3, sal4), greatest(sal1, sal2, sal3, sal4))
then sal1
end) as sal4
from t;
这仍假设四个sal
值不是NULL
。
答案 1 :(得分:0)
合并排序
select Acc_nbr, greatest(sal1,sal2) salA, least(sal3,sal4) salB
from (
select Acc_nbr, sal1, least(sal2,sal3) sal2, greatest(sal2,sal3) sal3, sal4
from (
select Acc_nbr, least(sal1,sal2) sal1, greatest(sal1,sal2) sal2, least(sal3,sal4) sal3, greatest(sal3,sal4) sal4
from tbl
) t1
) t2;
可以包装成单个选择,它会更加冗长。