根据发生标志更改

时间:2019-11-14 11:40:33

标签: sql

我将下表作为输入

id|type
1|manager
1|non manager
1|manager
1|non manager
1|non manager
1|manager

所需的输出: 如果属于经理人和非经理人的ID超过一​​个,则应如下所示。

id|type
1|mixed

任何人都可以帮助..

1 个答案:

答案 0 :(得分:2)

一种方法使用窗口函数:

select id,
       (case when max(type) over (partition by id) =
                  min(type) over (partition by id)
             then max(type) over (partition by id)
             else 'Mixed'
        end) as type
from t;

或者,也想到exists

select id,
       (case when exists (select 1
                          from t t2
                          where t2.id = t.id and t2.type <> t.type
                         )
             then 'Mixed' else type
        end) as type
from t;

编辑:

要获取每个ID一行,只需使用聚合:

select id,
       (case when max(type) = min(type)
             then max(type)
             else 'Mixed'
        end) as type
from t
group by id;