简体   繁体   中英

How to filter rows in SQL statement for aggregate function by window function?

I have some table and provide tools to the user to generate new columns based on existings.

Table:

+---+
|  a|
+---+
|  0|
|  1|
|  2|
|  3|
|  4|
|  5|
+---+

New column name: b

New column rule must be like: max(a) over(WHERE a < 3)

How to correct write this?

Result must be like SQL statement: SELECT *, (SELECT max(a) FROM table WHERE a < 3) as b FROM table . And returns:

+---+---+
|  a|  b|
+---+---+
|  0|  2|
|  1|  2|
|  2|  2|
|  3|  2|
|  4|  2|
|  5|  2|
+---+---+

But I can't wrote inside over() WHERE statement and can't allow user to know name of table. How do I solve this problem?

Just use a window function with case :

select a, max(case when a < 3 then a end) over () as b
from t;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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