在每个模数中,我想从类列中选择最差的类值,但只从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中,只有P'' y'在每一行中填充P.
答案 0 :(得分:2)
以下查询获取您想要的查询内容:
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
添加一个。