[英]How to set rows with max value within group as true sql
I have a table similar to this:我有一个类似这样的表:
ID ![]() |
ORDER![]() |
AGE![]() |
---|---|---|
12 ![]() |
34 ![]() |
50 ![]() |
99 ![]() |
41 ![]() |
17 ![]() |
12 ![]() |
34 ![]() |
24 ![]() |
99 ![]() |
42 ![]() |
12 ![]() |
12 ![]() |
33 ![]() |
15 ![]() |
12 ![]() |
33 ![]() |
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 ![]() |
ORDER![]() |
AGE![]() |
ACTIVE![]() |
---|---|---|---|
12 ![]() |
34 ![]() |
50 ![]() |
TRUE![]() |
99 ![]() |
41 ![]() |
17 ![]() |
FALSE![]() |
12 ![]() |
34 ![]() |
24 ![]() |
TRUE![]() |
99 ![]() |
42 ![]() |
12 ![]() |
TRUE![]() |
12 ![]() |
33 ![]() |
15 ![]() |
FALSE![]() |
12 ![]() |
33 ![]() |
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.