获取另一列的最大值对应的值
我需要找到另一列的最大值对应的值。
我的数据如下:
group | subgroup | subgroup_2 | value_a | value_b | date |
---|---|---|---|---|---|
A | 101 | 1 | 200 | 101 | 20220301 |
A | 102 | 1 | 105 | 90 | 20220301 |
A | 103 | 2 | 90 | 202 | 20220301 |
A | 211 | 2 | 75 | 107 | 20220301 |
B | 212 | 1 | 91 | 65 | 20220301 |
B | 213 | 1 | 175 | 101 | 20220301 |
我需要像这样格式化数据:
group | subgroup_2 | max_value_a | value_b | date |
---|---|---|---|---|
A | 1 | 200 | 101 | 20220301 |
A | 2 | 90 | 202 | 20220301 |
B | 1 | 175 | 101 | 20220301 |
我可以通过 group by 相当轻松地实现该格式,但是我必须聚合 value_b 才能执行此操作,这不会给我所需的结果。
我知道我可以在分区上使用rank(),但它似乎没有提供我需要的格式。
这是我在下面使用的查询,但它仅提供一个 subgroup_2 的最大值,而不是每个的最大值:
select group, subgroup_2, max_value_a, value_b, date
from
(
select a.group, a.subgroup_2, a.max_value_a, a.value_b, a.date,
rank() over(partition by a.group, subgroup_2, a.date order by a.max_value_a desc) as rnk
from table_1 a
)s
where rnk=1
I need to find the corresponding value to the max value of another column.
My data is as below:
group | subgroup | subgroup_2 | value_a | value_b | date |
---|---|---|---|---|---|
A | 101 | 1 | 200 | 101 | 20220301 |
A | 102 | 1 | 105 | 90 | 20220301 |
A | 103 | 2 | 90 | 202 | 20220301 |
A | 211 | 2 | 75 | 107 | 20220301 |
B | 212 | 1 | 91 | 65 | 20220301 |
B | 213 | 1 | 175 | 101 | 20220301 |
I would need to format the data like this:
group | subgroup_2 | max_value_a | value_b | date |
---|---|---|---|---|
A | 1 | 200 | 101 | 20220301 |
A | 2 | 90 | 202 | 20220301 |
B | 1 | 175 | 101 | 20220301 |
I can achieve the format fairly easily via a group by, however I have to aggregate value_b to do this which doesn't give me the result I need.
I know I can use rank() over partition by but it doesn't seem to provide the format I require.
This is the query I used below, however it only provides the max of one subgroup_2 rather than the max of each:
select group, subgroup_2, max_value_a, value_b, date
from
(
select a.group, a.subgroup_2, a.max_value_a, a.value_b, a.date,
rank() over(partition by a.group, subgroup_2, a.date order by a.max_value_a desc) as rnk
from table_1 a
)s
where rnk=1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您想在此处使用
ROW_NUMBER
:You want to use
ROW_NUMBER
here: