Sql 选择分区(层次结构)中最差的值

Sql 选择分区(层次结构)中最差的值,sql,oracle,Sql,Oracle,在每个模数中,我想从类列中选择最差的类值,但只能从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/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”的行,因此为空;在模“3”中,有两个带“y”的值:P和S。最差的是S。在模“4”中,只有带“y”的P,因此在每一行中填充P。

以下查询得到您想要的查询:

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
      )

这假设您有一个最差类的列。如果您没有,那么您需要使用
altertable

添加一个,我不知道有什么问题,但我一直得到:“缺少右括号”@FrankMoses。我道歉。不知怎的,我把MySQL读作数据库。我修正了Oracle语法的答案。