简体   繁体   English

如何将组内最大值的行设置为真 sql

[英]How to set rows with max value within group as true sql

I have a table similar to this:我有一个类似这样的表:

ID ID ORDER命令 AGE年龄
12 12 34 34 50 50
99 99 41 41 17 17
12 12 34 34 24 24
99 99 42 42 12 12
12 12 33 33 15 15
12 12 33 33 38 38

I would like to look at the ID column, where if the ORDER value is the max value within the ID group, then to set it as TRUE, and the others as FALSE.我想查看 ID 列,如果 ORDER 值是 ID 组中的最大值,则将其设置为 TRUE,将其他设置为 FALSE。

I tried to do我试着做


SELECT ID, ORDER,
CASE WHEN ORDER = MAX(ORDER) THEN TRUE ELSE FALSE END AS ACTIVE
FROM MY_TABLE
GROUP BY ID, ORDER;

But that seems to just set every ACTIVE value to true.但这似乎只是将每个 ACTIVE 值设置为 true。

Ultimately I am trying to end up with a table like最终我试图得到一张像这样的桌子

ID ID ORDER命令 AGE年龄 ACTIVE积极的
12 12 34 34 50 50 TRUE真的
99 99 41 41 17 17 FALSE错误的
12 12 34 34 24 24 TRUE真的
99 99 42 42 12 12 TRUE真的
12 12 33 33 15 15 FALSE错误的
12 12 33 33 38 38 FALSE错误的

What would be the best way to achieve this?实现这一目标的最佳方法是什么? Thanks!谢谢!

Use MAX() window function:使用MAX() window function:

SELECT ID, ORDER, AGE,
       ORDER = MAX(ORDER) OVER (PARTITION BY ID) AS ACTIVE
FROM MY_TABLE;

You will want to rank the rows using row_number.您将希望使用 row_number 对行进行排名。 Order by order and partition by id .order并按id分区。 This will provide you with a rank value where you can set the Active flag where rank = 1 .这将为您提供一个排名值,您可以在其中设置Active标志where rank = 1

https://docs.snowflake.com/en/sql-reference/functions/row_number.html https://docs.snowflake.com/en/sql-reference/functions/row_number.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM