如何设置多组的标志

5cg8jx4n  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(467)

我有一个返回的查询(带有一些join/logis/不同的表):

SELECT WorkTypeId, WorktypeWorkID, LevelID
    FROM Worktypes as w
    LEFT JOIN WorktypesWorks as ww on w.ID = ww.WorktypeID
    LEFT JOIN WorktypesWorksLevels as wwl on ww.ID = wwl.WorktypeWorkID
    ORDER BY w.ID, ww.ID, wwl.LevelID

结果如下:

WorkTypeId  WorktypeWorkID  LevelID
1           1               1
1           1               2
1           1               3
1           2               1
1           2               2
1           2               3
1           3               1
1           4               1
1           4               2
1           5               1
4           6               1
4           7               1
4           7               2
4           7               3

我想为每一行添加一个额外的列(即islast),如果对于每个worktypeid组,(第一个)子组worktypeworkid包含较小的levelid,则返回true。
在上面的例子中,结果应该是:

WorkTypeId  WorktypeWorkID  LevelID IsLast
1           1               1       false
1           1               2       false
1           1               3       false
1           2               1       false
1           2               2       false
1           2               3       false
1           3               1       true
1           4               1       false
1           4               2       false
1           5               1       false
4           6               1       true
4           7               1       false
4           7               2       false
4           7               3       false

我该怎么做?基本上:
按worktypeworkid分组获取最大levelid并首先获取
groupby worktypeid从上一个组获取mix levelid
添加标志

tpgth1q7

tpgth1q71#

你好像想要最小的 WorktypeWorkID 它只包含行。如果是:

select t.*,
       (case when cnt = 1 and
                  dense_rank() over (partition by WorkTypeId, cnt order by WorktypeWorkID) = 1
             then 1 else 0
        end) as islast
from (select t.*, count(*) over (partition by WorkTypeId, WorktypeWorkID) as cnt
      from t
     ) t;

相关问题