比较3字段大小并判断和第4个字段的关系: 比较头痛!
列3 列1 列0 列N 产生列
0.87 0.96 1.01 3 X
0.89 0.92 0.88 1 D
0.95 0.94 0.85 0 X
0.92 0.91 0.89 1 Z
0.91 0.90 0.94 1 X
0.89 0.91 0.94 3 X
0.86 0.89 0.97 3 X
0.85 0.91 0.94 1 Z
0.89 0.91 0.95 3 X
0.90 0.90 0.88 3 D
0.94 0.89 0.89 1 X
0.90 0.92 0.91 3 X
0.91 0.87 0.92 3 Z
0.90 0.91 0.93 1 Z
0.98 0.91 0.78 3 D
0.89 0.90 0.95 1 Z
0.93 0.85 0.95 3 Z
如何产生以上效果:
说明:X(小)D(大)Z(中)
0.87 0.96 1.01 3 X(首先看列N,是3,然后用列3比较列1,0 可以发现列3是最小的,所以应该是X)
0.89 0.92 0.88 1 D(首先看列N,是1,然后用列1比较列3,0 可以发现列1是最大的,所以应该是D)
0.93 0.85 0.95 3 Z(首先看列N,是3,然后用列3比较列1,0 可以发现列3是中间的,所以应该是Z)
0.89 0.90 0.95 1 Z(首先看列N,是1,然后用列1比较列3,0 可以发现列1是中间的,所以应该是Z)
0.90 0.90 0.88 3 D(首先看列N,是3,然后用列3比较列1,0 可以发现列3是最大的,当然列1也是最大的,这样按照最大,所以应该是D)
不知道意思描述的可否清晰,请大家帮助!
--环境
create table tt
(
列3 decimal(5,2),
列1 decimal(5,2),
列0 decimal(5,2),
列N int
)
insert into tt select 0.87, 0.96, 1.01, 3
insert into tt select 0.89, 0.92, 0.88, 1
insert into tt select 0.95, 0.94, 0.85, 0
insert into tt select 0.92, 0.91, 0.89, 1
insert into tt select 0.91, 0.90, 0.94, 1
insert into tt select 0.89, 0.91, 0.94, 3
insert into tt select 0.86, 0.89, 0.97, 3
insert into tt select 0.85, 0.91, 0.94, 1
insert into tt select 0.89, 0.91, 0.95, 3
insert into tt select 0.90, 0.90, 0.88, 3
insert into tt select 0.94, 0.89, 0.89, 1
insert into tt select 0.90, 0.92, 0.91, 3
insert into tt select 0.91, 0.87, 0.92, 3
insert into tt select 0.90, 0.91, 0.93, 1
insert into tt select 0.98, 0.91, 0.78, 3
insert into tt select 0.89, 0.90, 0.95, 1
insert into tt select 0.93, 0.85, 0.95, 3
--语句
select *,产生列 = (case when 列3 >= 列1 and 列3 >= 列0 then 'D'
when (列3 - 列1)*(列3 - 列0) < 0 then 'Z' else 'X' end)
from tt
where 列N = 3
union
select *,产生列 = (case when 列1 >= 列3 and 列1 >= 列0 then 'D'
when (列1 - 列3)*(列1 - 列0) < 0 then 'Z' else 'X' end)
from tt
where 列N = 1
union
select *,产生列 = (case when 列0 >= 列3 and 列0 >= 列1 then 'D'
when (列0 - 列1)*(列0 - 列3) < 0 then 'Z' else 'X' end)
from tt
where 列N = 0
--结果
.85 .91 .94 1 Z
.86 .89 .97 3 X
.87 .96 1.01 3 X
.89 .90 .95 1 Z
.89 .91 .94 3 X
.89 .91 .95 3 X
.89 .92 .88 1 D
.90 .90 .88 3 D
.90 .91 .93 1 Z
.90 .92 .91 3 X
.91 .87 .92 3 Z
.91 .90 .94 1 X
.92 .91 .89 1 Z
.93 .85 .95 3 Z
.94 .89 .89 1 X
.95 .94 .85 0 X
.98 .91 .78 3 D
--删除环境
drop table tt
--PS
排序没有做好,楼主可根据表里的主键排序
感谢 coolingpipe(冷箫轻笛) marco08(天道酬勤)
我开始也是使用了
select 列3,列1,列0,列N,
case
when (列N='3' and 列3<列1 and 列3<列0) then 'X'
when (列N='1' and 列1<列3 and 列1<列0) then 'X'
when (列N='0' and 列0<列3 and 列0<列1) then 'X'
............
when (列N='3' and 列3>列1 and 列3>列0) then 'D'
when (列N='1' and 列1>列3 and 列1>列0) then 'D'
when (列N='0' and 列0>列3 and 列0>列1) then 'D'
end as maxid from #t1
这样,但是自己采用了最笨得办法!列举关系,但是判断 中间(Z)的时候错误了!
感谢2位!