【问题标题】:Add a columns who tags the max and min value of a column添加标记列的最大值和最小值的列
【发布时间】:2021-03-08 16:42:07
【问题描述】:

我想添加一个额外的列,其中将显示每个组 (ID) 的最小值和最大值。 表格如下所示:

从 mytable 中选择 ID、VALUE

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

提前感谢您的帮助!

【问题讨论】:

  • 请向我们展示您的尝试。

标签: sql sql-server max case min


【解决方案1】:

您可以使用窗口函数和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

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

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-25
  • 2018-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多