添加标记列的最大值和最小值的列

Add a columns who tags the max and min value of a column

我想添加一个额外的列,其中将显示每个组 (ID) 的最小值和最大值。 table 的样子:

select ID,VALUE 来自我的table

ID VALUE
1 4
1 1
1 7
2 2
2 5
3 7
3 3

这是我想要得到的结果:

ID VALUE min_max_values
1 4 NULL
1 1 min
1 7 max
2 2 min
2 5 max
3 7 max
3 3 min
4 1 both
5 2 min
5 3 max

提前感谢您的帮助!

您可以使用 window 函数和 case 表达式:

select id, value,
    case
        when value = min_value and min_value = max_value then 'both'
        when value = min_value then 'min'
        when value = max_value then 'max'
    end as min_max_values
from (
    select t.*,
        min(value) over(partition by id) as min_value,
        max(value) over(partition by id) as max_value
    from mytable t
) t

子查询不是绝对必要的,我们可以在外部查询中直接使用window min()max()。它只是为了避免在外部查询中重复输入 window 函数表达式。