在每个模数中,我希望从类列中选择最差的类值,但只从y/n列中带有'y‘的行中选择类值,然后为每个模块在每一行中填充该类。我不知道如何实现层次结构,即:
N优于O,O优于P,P优于W,W优于S (S是最差类)
示例:
modulo y/n class
1 y N
1 n P
1 n W
1 y P
2 n W
2 n N
3 y P
3 y W
3 n O
2 y W
4 n P
4 y S我想达到的目标是:
modulo y/n class worst_class
1 y N W
1 n P W
1 n W W
1 y P W
2 n W
2 n N
3 y P S
3 y S S
3 n O S
1 y W W
4 n S P
4 y P P在模'1‘中,只有’y‘的三个值: N,P和W,最坏的值是W,所以模'1’中的每一行都填充W。在模'2‘中没有'y’所以NULL的行,在模'3‘中有两个'y’值:P和S,最差的是S,在模'4‘中,每一行中只有’y‘的P填充P。
发布于 2013-07-25 15:39:31
下面的查询获取您想要的查询:
select m.*, mm.WorstClass
from modulo m left outer join
(select modulo,
(case when SUM(case when class = 'S' then 1 else 0 end) > 0 then 'S'
when sum(case when class = 'W' then 1 else 0 end) > 0 then 'W'
when sum(case when class = 'P' then 1 else 0 end) > 0 then 'P'
when sum(case when class = 'O' then 1 else 0 end) > 0 then 'O'
when sum(case when class = 'N' then 1 else 0 end) > 0 then 'N'
end) as WorstClass
from modulo
where YN = 'y'
group by modulo
) mm
on m.modulo = mm.modulo;因为这是Oracle,所以更新需要使用关联子查询:
update modulo m
set WorstClass =
(select (case when SUM(case when class = 'S' then 1 else 0 end) > 0 then 'S'
when sum(case when class = 'W' then 1 else 0 end) > 0 then 'W'
when sum(case when class = 'P' then 1 else 0 end) > 0 then 'P'
when sum(case when class = 'O' then 1 else 0 end) > 0 then 'O'
when sum(case when class = 'N' then 1 else 0 end) > 0 then 'N'
end) as WorstClass
from modulo mm
where YN = 'y' and mm.module = m.modulo
)这假设您有一个列用于最差类。如果没有,则需要使用alter table添加一个。
https://stackoverflow.com/questions/17862007
复制相似问题