SQL按案例语句和标志进行分区

时间:2019-12-04 19:09:23

标签: sql

我遇到了一个问题,

该表由col2按值BB和CC划分,并且在col3中具有它们各自的状态,我想要对col2中的每一行应用标志,例如,如果col2中的任何或所有行的状态为' ST_Inprogress”或“ ST_Approved”,那么col2中所有行的标志应为“ Y”,否则应为“ N”,如所附图片中的给定表

enter image description here

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

具有MAX()窗口功能:

select *,
  max(case when Col3 in ('ST_Inprogress', 'ST_Approved') then 'Y' else 'N' end) over (partition by Col2) flag
from tablename

请参见PostgresqlSQL Server的演示。
结果:

| Col1 | Col2 | Col3        | flag |
| ---- | ---- | ----------- | ---- |
| AA   | BB   | ST_Closed   | N    |
| AA   | BB   | ST_Closed   | N    |
| AA   | BB   | ST_Deleted  | N    |
| AA   | BB   | ST_Closed   | N    |
| AA   | BB   | ST_Deleted  | N    |
| AA   | BB   | ST_Deleted  | N    |
| AA   | BB   | ST_Deleted  | N    |
| AA   | BB   | ST_Deleted  | N    |
| AA   | BB   | ST_Deleted  | N    |
| AA   | BB   | ST_Deleted  | N    |
| AA   | BB   | ST_Deleted  | N    |
| AA   | BB   | ST_Deleted  | N    |
| AA   | CC   | ST_Deleted  | Y    |
| AA   | CC   | ST_Approved | Y    |
| AA   | CC   | ST_Deleted  | Y    |
| AA   | CC   | ST_Deleted  | Y    |
| AA   | CC   | ST_Deleted  | Y    |
| AA   | CC   | ST_Deleted  | Y    |
| AA   | CC   | ST_Deleted  | Y    |
| AA   | CC   | ST_Deleted  | Y    |
| AA   | CC   | ST_Deleted  | Y    |
| AA   | CC   | ST_Deleted  | Y    |
| AA   | CC   | ST_Approved | Y    |