获取另一列的最大值对应的值

发布于 2025-01-13 20:35:39 字数 1676 浏览 2 评论 0原文

我需要找到另一列的最大值对应的值。

我的数据如下:

groupsubgroupsubgroup_2value_avalue_bdate
A101120010120220301
A10211059020220301
A10329020220220301
A21127510720220301
B2121916520220301
B213117510120220301

我需要像这样格式化数据:

groupsubgroup_2max_value_avalue_bdate
A120010120220301
A29020220220301
B117510120220301

我可以通过 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:

groupsubgroupsubgroup_2value_avalue_bdate
A101120010120220301
A10211059020220301
A10329020220220301
A21127510720220301
B2121916520220301
B213117510120220301

I would need to format the data like this:

groupsubgroup_2max_value_avalue_bdate
A120010120220301
A29020220220301
B117510120220301

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

追风人 2025-01-20 20:35:39

您想在此处使用 ROW_NUMBER

SELECT group, subgroup_2, value_a AS max_value_a, value_b, date
FROM
(
    SELECT group, subgroup_2, value_a, value_b, date,
           ROW_NUMBER() OVER (PARTITION BY group, subgroup_2 ORDER BY value_a DESC) rn
    FROM table_1
) t
WHERE rn = 1;

You want to use ROW_NUMBER here:

SELECT group, subgroup_2, value_a AS max_value_a, value_b, date
FROM
(
    SELECT group, subgroup_2, value_a, value_b, date,
           ROW_NUMBER() OVER (PARTITION BY group, subgroup_2 ORDER BY value_a DESC) rn
    FROM table_1
) t
WHERE rn = 1;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文