如何将标志设置为组的最大数量?

问题描述 投票:0回答:1

这是查询:

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

这是结果:

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
NULL        NULL            NULL
3           19              2
4           6               1
4           7               1
4           7               2
4           7               3
4           17              1
4           17              2
4           18              1
4           18              2
NULL            NULL        NULL

我只想将一个名为“ MaxLevel”的新列添加到其中LevelID(对于每个具有相同WorkTypeId的WorktypeWorkID组)设置为1的行(如果LevelID是该组中的MAX号,则为0,否则为0) 。

这是我想要得到的结果:

WorkTypeId  WorktypeWorkID  LevelID     MaxLevel
1           1               1           0
1           1               2           0
1           1               3           1 // 3 is the max on the group
1           2               1           0
1           2               2           0
1           2               3           1 // 3 is the max on the group
1           3               1           1 // 1 is the max on the group
1           4               1           0
1           4               2           1 // 2 is the max on the group
1           5               1           1 // 1 is the max on the group
NULL        NULL            NULL        0
3           19              2           1 // 2 is the max on the group
4           6               1           1 // 1 is the max on the group
4           7               1           0
4           7               2           0
4           7               3           1 // 3 is the max on the group
4           17              1           0
4           17              2           1 // 2 is the max on the group
4           18              1           0
4           18              2           1 // 2 is the max on the group
NULL            NULL        NULL        0
sql sql-server group-by max
1个回答
0
投票
您可以使用窗口功能:

0
投票
这只是一个CASE表达式和一个带窗口的MAX,就像我在评论中提到的那样:

0
投票
由于NULL值,这有点棘手。所以我认为你想要:
© www.soinside.com 2019 - 2024. All rights reserved.