例如,我有一个这样的表:
+---------+-------+----------+
| sort_id | level | security |
+---------+-------+----------+
| 1 | 1 | A |
| 2 | 2 | A |
| 3 | 3 | U |
| 4 | 4 | A |
| 5 | 5 | A |
| 6 | 3 | A |
| 7 | 4 | U |
| 8 | 5 | A |
| 9 | 6 | A |
| 10 | 7 | A |
| 11 | 3 | A |
| 12 | 3 | A |
+---------+-------+----------+
安全栏是A代表授权,U代表未授权。我需要根据他们的级别排除未授权记录下的那些记录。 为了更好地了解SQL记录,它看起来像这样:
带有箭头的那些是未经授权的记录,我们应该排除其下的记录。
所以SQL结果应该是下表:
+---------+-------+----------+
| sort_id | level | security |
+---------+-------+----------+
| 1 | 1 | A |
| 2 | 2 | A |
| 3 | 3 | U |
| 6 | 3 | A |
| 7 | 4 | U |
| 11 | 3 | A |
| 12 | 3 | A |
+---------+-------+----------+
我们如何使用简单的Select语句生成它?提前致谢!如果有什么不清楚,请评论。
答案 0 :(得分:1)
如果我理解"未经授权的记录"作为一个记录序列,其ID越来越大,跟随未经授权的记录(基于id),这是一种方法:
select sort_id, level, security
from (select t.*, min(case when authorized = 'U' then id end) over (partition by grp) as minuid
from (select t.*,
(row_number() over (order by id) - level) as grp
from table t
) t
) t
where id > minuid;