在ORDER BY
子句中有一个没有OVER ()
的窗口函数。是否可以保证将按SELECT本身中ORDER BY
表达式指定的顺序处理行?
例如:
SELECT tt.*
, row_number() OVER (PARTITION BY tt."group") AS npp --without ORDER BY
FROM
(
SELECT SUBSTRING(random() :: text, 3, 1) AS "group"
, random() :: text AS "data"
FROM generate_series(1, 100) t(ser)
ORDER BY "group", "data"
) tt
ORDER BY tt."group", npp;
在此示例中,子查询返回每个组中按升序排序的data
。窗口函数以相同的顺序处理行,因此行号以data
的升序排列。我可以依靠吗?
答案 0 :(得分:2)
Good question!
No, you cannot rely on that.
Window functions are processed before the query's ORDER BY
clause, and without an ORDER BY
in the window definition, the rows will be processed in the order in which they happen to come from the subselect.
答案 1 :(得分:0)
if you use an order by
in your over ()
row_number() OVER (PARTITION BY tt."group" ORDER BY tt."group")
you should get the order you want.