/
window-functions.rst
730 lines (565 loc) · 20.9 KB
/
window-functions.rst
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
.. highlight:: psql
.. _window-functions:
================
Window functions
================
Window functions are :ref:`functions <gloss-function>` which perform a
computation across a set of rows which are related to the current row. This is
comparable to :ref:`aggregation functions <aggregation-functions>`, but window
functions do not cause multiple rows to be grouped into a single row.
.. rubric:: Table of contents
.. contents::
:local:
.. _window-function-call:
Window function call
====================
.. _window-call-synopsis:
Synopsis
--------
The synopsis of a window function call is one of the following
::
function_name ( { * | [ expression [, expression ... ] ] } )
[ FILTER ( WHERE condition ) ]
[ { RESPECT | IGNORE } NULLS ]
over_clause
where ``function_name`` is a name of a :ref:`general-purpose window
<window-functions-general-purpose>` or :ref:`aggregate function
<aggregation-functions>` and ``expression`` is a column reference, :ref:`scalar
function <scalar-functions>` or literal.
If ``FILTER`` is specified, then only the rows that met the :ref:`WHERE
<sql-select-where>` condition are supplied to the window function. Only window
functions that are :ref:`aggregates <aggregation>` accept the ``FILTER``
clause.
If ``IGNORE NULLS`` option is specified, then the null values are excluded from
the window function executions. The window functions that support this option
are: :ref:`window-functions-lead`, :ref:`window-functions-lag`,
:ref:`window-functions-first-value`, :ref:`window-functions-last-value`,
and :ref:`window-functions-nth-value`. If a function supports this option and
it is not specified, then ``RESPECT NULLS`` is set by default.
The :ref:`window-definition-over` clause is what declares a function to be a
window function.
The window function call that uses a ``wildcard`` instead of an ``expression``
as a function argument is supported only by the ``count(*)`` aggregate
function.
.. _window-definition:
Window definition
=================
.. _window-definition-over:
OVER
----
.. _window-definition-over-synopsis:
Synopsis
........
::
OVER { window_name | ( [ window_definition ] ) }
where ``window_definition`` has the syntax
::
window_definition:
[ window_name ]
[ PARTITION BY expression [, ...] ]
[ ORDER BY expression [ ASC | DESC ] [ NULLS { FIRST | LAST } ] [, ...] ]
[ { RANGE | ROWS } BETWEEN frame_start AND frame_end ]
The ``window_name`` refers to ``window_definition`` defined in the
:ref:`WINDOW <sql-select-window>` clause.
The ``frame_start`` and ``frame_end`` can be one of
::
UNBOUNDED PRECEDING
offset PRECEDING
CURRENT ROW
offset FOLLOWING
UNBOUNDED FOLLOWING
The default frame definition is ``RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT
ROW``. If ``frame_end`` is omitted it defaults to ``CURRENT ROW``.
``frame_start`` cannot be ``FOLLOWING`` or ``UNBOUNDED FOLLOWING`` and
``frame_end`` cannot be ``PRECEDING`` or ``UNBOUNDED PRECEDING``.
In ``RANGE`` mode if the ``frame_start`` is ``CURRENT ROW`` the frame starts
with the current row's first peer (a row that the window's ``ORDER BY``
:ref:`expression <gloss-expression>` sorts as equal to the current row), while
a ``frame_end`` of ``CURRENT ROW`` means the frame will end with the current's
row last peer row.
In ``ROWS`` mode ``CURRENT_ROW`` means the current row.
The ``offset PRECEDING`` and ``offset FOLLOWING`` options vary in meaning
depending on the frame mode. In ``ROWS`` mode, the ``offset`` is an integer
indicating that the frame start or end is offsetted by that many rows before or
after the current row. In ``RANGE`` mode, the use of a custom ``offset`` option
requires that there is exactly one ``ORDER BY`` column in the window
definition. The frame contains those rows whose ordering column value is no
more than ``offset`` minus (for ``PRECEDING``) or plus (for ``FOLLOWING``) the
current row's ordering column value. Because the value of ``offset`` is
subtracted/added to the values of the ordering column, only type combinations
that support addition/subtraction operations are allowed. For instance, when
the ordering column is of type :ref:`timestamp <type-timestamp>`, the
``offset`` expression can be an :ref:`interval <type-interval>`.
The :ref:`window-definition-over` clause defines the ``window`` containing the
appropriate rows which will take part in the ``window function`` computation.
An empty :ref:`window-definition-over` clause defines a ``window`` containing
all the rows in the result set.
Example::
cr> SELECT dept_id, COUNT(*) OVER() AS cnt FROM employees ORDER BY 1, 2;
+---------+-----+
| dept_id | cnt |
+---------+-----+
| 4001 | 18 |
| 4001 | 18 |
| 4001 | 18 |
| 4002 | 18 |
| 4002 | 18 |
| 4002 | 18 |
| 4002 | 18 |
| 4003 | 18 |
| 4003 | 18 |
| 4003 | 18 |
| 4003 | 18 |
| 4003 | 18 |
| 4004 | 18 |
| 4004 | 18 |
| 4004 | 18 |
| 4006 | 18 |
| 4006 | 18 |
| 4006 | 18 |
+---------+-----+
SELECT 18 rows in set (... sec)
The ``PARTITION BY`` clause groups the rows within a window into
partitions which are processed separately by the window function, each
partition in turn becoming a window. If ``PARTITION BY`` is not specified, all
the rows are considered a single partition.
Example::
cr> SELECT dept_id, ROW_NUMBER() OVER(PARTITION BY dept_id) AS row_num
... FROM employees ORDER BY 1, 2;
+---------+---------+
| dept_id | row_num |
+---------+---------+
| 4001 | 1 |
| 4001 | 2 |
| 4001 | 3 |
| 4002 | 1 |
| 4002 | 2 |
| 4002 | 3 |
| 4002 | 4 |
| 4003 | 1 |
| 4003 | 2 |
| 4003 | 3 |
| 4003 | 4 |
| 4003 | 5 |
| 4004 | 1 |
| 4004 | 2 |
| 4004 | 3 |
| 4006 | 1 |
| 4006 | 2 |
| 4006 | 3 |
+---------+---------+
SELECT 18 rows in set (... sec)
If ``ORDER BY`` is supplied the ``window`` definition consists of a range of
rows starting with the first row in the ``partition`` and ending with the
current row, plus any subsequent rows that are equal to the current row, which
are the current row's ``peers``.
Example::
cr> SELECT
... dept_id,
... sex,
... COUNT(*) OVER(PARTITION BY dept_id ORDER BY sex) AS cnt
... FROM employees
... ORDER BY 1, 2, 3
+---------+-----+-----+
| dept_id | sex | cnt |
+---------+-----+-----+
| 4001 | M | 3 |
| 4001 | M | 3 |
| 4001 | M | 3 |
| 4002 | F | 1 |
| 4002 | M | 4 |
| 4002 | M | 4 |
| 4002 | M | 4 |
| 4003 | M | 5 |
| 4003 | M | 5 |
| 4003 | M | 5 |
| 4003 | M | 5 |
| 4003 | M | 5 |
| 4004 | F | 1 |
| 4004 | M | 3 |
| 4004 | M | 3 |
| 4006 | F | 1 |
| 4006 | M | 3 |
| 4006 | M | 3 |
+---------+-----+-----+
SELECT 18 rows in set (... sec)
.. NOTE::
Taking into account the ``peers`` concept mentioned above, for an empty
:ref:`window-definition-over` clause all the rows in the result set are
``peers``.
.. NOTE::
:ref:`Aggregation functions <aggregation>` will be treated as ``window
functions`` when used in conjunction with the :ref:`window-definition-over`
clause.
.. NOTE::
Window definitions order or partitioned by an array column type are
currently not supported.
In the ``UNBOUNDED FOLLOWING`` case the ``window`` for each row starts with
each row and ends with the last row in the current ``partition``. If the
``current row`` has ``peers`` the ``window`` will include (or start with) all
the ``current row`` peers and end at the upper bound of the ``partition``.
Example::
cr> SELECT
... dept_id,
... sex,
... COUNT(*) OVER(
... PARTITION BY dept_id
... ORDER BY
... sex RANGE BETWEEN CURRENT ROW
... AND UNBOUNDED FOLLOWING
... ) partitionByDeptOrderBySex
... FROM employees
... ORDER BY 1, 2, 3
+---------+-----+---------------------------+
| dept_id | sex | partitionbydeptorderbysex |
+---------+-----+---------------------------+
| 4001 | M | 3 |
| 4001 | M | 3 |
| 4001 | M | 3 |
| 4002 | F | 4 |
| 4002 | M | 3 |
| 4002 | M | 3 |
| 4002 | M | 3 |
| 4003 | M | 5 |
| 4003 | M | 5 |
| 4003 | M | 5 |
| 4003 | M | 5 |
| 4003 | M | 5 |
| 4004 | F | 3 |
| 4004 | M | 2 |
| 4004 | M | 2 |
| 4006 | F | 3 |
| 4006 | M | 2 |
| 4006 | M | 2 |
+---------+-----+---------------------------+
SELECT 18 rows in set (... sec)
.. _window-definition-named-windows:
Named windows
-------------
It is possible to define a list of named window definitions that can be
referenced in :ref:`window-definition-over` clauses. To do this, use the
:ref:`sql-select-window` clause in the :ref:`sql-select` clause.
Named windows are particularly useful when the same window definition
could be used in multiple :ref:`window-definition-over` clauses. For instance
::
cr> SELECT
... x,
... FIRST_VALUE(x) OVER (w) AS "first",
... LAST_VALUE(x) OVER (w) AS "last"
... FROM (VALUES (1), (2), (3), (4)) AS t(x)
... WINDOW w AS (ORDER BY x)
+---+-------+------+
| x | first | last |
+---+-------+------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 1 | 3 |
| 4 | 1 | 4 |
+---+-------+------+
SELECT 4 rows in set (... sec)
If a ``window_name`` is specified in the window definition of the
:ref:`window-definition-over` clause, then there must be a named window entry
that matches the ``window_name`` in the window definition list of the
:ref:`sql-select-window` clause.
If the :ref:`window-definition-over` clause has its own non-empty window
definition and references a window definition from the :ref:`sql-select-window`
clause, then it can only add clauses from the referenced window, but not
overwrite them.
::
cr> SELECT
... x,
... LAST_VALUE(x) OVER (w ORDER BY x) AS y
... FROM (VALUES
... (1, 1),
... (2, 1),
... (3, 2),
... (4, 2) ) AS t(x, y)
... WINDOW w AS (PARTITION BY y)
+---+---+
| x | y |
+---+---+
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
+---+---+
SELECT 4 rows in set (... sec)
Otherwise, an attempt to override the clauses of the referenced window by the
window definition of the :ref:`window-definition-over` clause will result in
failure.
::
cr> SELECT
... FIRST_VALUE(x) OVER (w ORDER BY x)
... FROM (VALUES(1), (2), (3), (4)) as t(x)
... WINDOW w AS (ORDER BY x)
SQLParseException[Cannot override ORDER BY clause of window w]
It is not possible to define the ``PARTITION BY`` clause in the window
definition of the :ref:`window-definition-over` clause if it references a
window definition from the :ref:`sql-select-window` clause.
The window definitions in the :ref:`sql-select-window` clause cannot define
its own window frames, if they are referenced by non-empty window definitions
of the :ref:`window-definition-over` clauses.
The definition of the named window can itself begin with a ``window_name``. In
this case all the elements of interconnected named windows will be copied to
the window definition of the :ref:`window-definition-over` clause if it
references the named window definition that has subsequent window
references. The window definitions in the ``WINDOW`` clause permits only
backward references.
::
cr> SELECT
... x,
... ROW_NUMBER() OVER (w) AS y
... FROM (VALUES
... (1, 1),
... (3, 2),
... (2, 1)) AS t (x, y)
... WINDOW p AS (PARTITION BY y),
... w AS (p ORDER BY x)
+---+---+
| x | y |
+---+---+
| 1 | 1 |
| 2 | 2 |
| 3 | 1 |
+---+---+
SELECT 3 rows in set (... sec)
.. _window-functions-general-purpose:
General-purpose window functions
================================
``row_number()``
----------------
Returns the number of the current row within its window.
Example::
cr> SELECT
... col1,
... ROW_NUMBER() OVER(ORDER BY col1) as row_num
... FROM (VALUES('x'), ('y'), ('z')) AS t;
+------+---------+
| col1 | row_num |
+------+---------+
| x | 1 |
| y | 2 |
| z | 3 |
+------+---------+
SELECT 3 rows in set (... sec)
.. _window-functions-first-value:
``first_value(arg)``
--------------------
Returns the argument value :ref:`evaluated <gloss-evaluation>` at the first row
within the window.
Its return type is the type of its argument.
Example::
cr> SELECT
... col1,
... FIRST_VALUE(col1) OVER (ORDER BY col1) AS value
... FROM (VALUES('x'), ('y'), ('y'), ('z')) AS t;
+------+-------+
| col1 | value |
+------+-------+
| x | x |
| y | x |
| y | x |
| z | x |
+------+-------+
SELECT 4 rows in set (... sec)
.. _window-functions-last-value:
``last_value(arg)``
-------------------
Returns the argument value :ref:`evaluated <gloss-evaluation>` at the last row
within the window.
Its return type is the type of its argument.
Example::
cr> SELECT
... col1,
... LAST_VALUE(col1) OVER(ORDER BY col1) AS value
... FROM (VALUES('x'), ('y'), ('y'), ('z')) AS t;
+------+-------+
| col1 | value |
+------+-------+
| x | x |
| y | y |
| y | y |
| z | z |
+------+-------+
SELECT 4 rows in set (... sec)
.. _window-functions-nth-value:
``nth_value(arg, number)``
--------------------------
Returns the argument value :ref:`evaluated <gloss-evaluation>` at row that is
the nth row within the window. ``NULL`` is returned if the nth row doesn't
exist in the window.
Its return type is the type of its first argument.
Example::
cr> SELECT
... col1,
... NTH_VALUE(col1, 3) OVER(ORDER BY col1) AS val
... FROM (VALUES ('x'), ('y'), ('y'), ('z')) AS t;
+------+------+
| col1 | val |
+------+------+
| x | NULL |
| y | y |
| y | y |
| z | y |
+------+------+
SELECT 4 rows in set (... sec)
.. _window-functions-lag:
``lag(arg [, offset [, default] ])``
------------------------------------
.. _window-functions-lag-synopsis:
Synopsis
........
::
lag(argument any [, offset integer [, default any]])
Returns the argument value :ref:`evaluated <gloss-evaluation>` at the row that
precedes the current row by the offset within the partition. If there is no
such row, the return value is ``default``. If ``offset`` or ``default``
arguments are missing, they default to ``1`` and ``null``, respectively.
Both ``offset`` and ``default`` are evaluated with respect to the current row.
If ``offset`` is ``0``, then argument value is evaluated for the current row.
The ``default`` and ``argument`` data types must match.
Example::
cr> SELECT
... dept_id,
... year,
... budget,
... LAG(budget) OVER(
... PARTITION BY dept_id) prev_budget
... FROM (VALUES
... (1, 2017, 45000),
... (1, 2018, 35000),
... (2, 2017, 15000),
... (2, 2018, 65000),
... (2, 2019, 12000))
... as t (dept_id, year, budget);
+---------+------+--------+-------------+
| dept_id | year | budget | prev_budget |
+---------+------+--------+-------------+
| 1 | 2017 | 45000 | NULL |
| 1 | 2018 | 35000 | 45000 |
| 2 | 2017 | 15000 | NULL |
| 2 | 2018 | 65000 | 15000 |
| 2 | 2019 | 12000 | 65000 |
+---------+------+--------+-------------+
SELECT 5 rows in set (... sec)
.. _window-functions-lead:
``lead(arg [, offset [, default] ])``
-------------------------------------
.. _window-functions-lead-synopsis:
Synopsis
........
::
lead(argument any [, offset integer [, default any]])
The ``lead`` function is the counterpart of the :ref:`lag window function
<window-functions-lag>` as it allows the :ref:`evaluation <gloss-evaluation>`
of the argument at rows that follow the current row. ``lead`` returns the
argument value evaluated at the row that follows the current row by the offset
within the partition. If there is no such row, the return value is ``default``.
If ``offset`` or ``default`` arguments are missing, they default to ``1`` or
``null``, respectively.
Both ``offset`` and ``default`` are evaluated with respect to the current row.
If ``offset`` is ``0``, then argument value is evaluated for the current row.
The ``default`` and ``argument`` data types must match.
Example::
cr> SELECT
... dept_id,
... year,
... budget,
... LEAD(budget) OVER(
... PARTITION BY dept_id) next_budget
... FROM (VALUES
... (1, 2017, 45000),
... (1, 2018, 35000),
... (2, 2017, 15000),
... (2, 2018, 65000),
... (2, 2019, 12000))
... as t (dept_id, year, budget);
+---------+------+--------+-------------+
| dept_id | year | budget | next_budget |
+---------+------+--------+-------------+
| 1 | 2017 | 45000 | 35000 |
| 1 | 2018 | 35000 | NULL |
| 2 | 2017 | 15000 | 65000 |
| 2 | 2018 | 65000 | 12000 |
| 2 | 2019 | 12000 | NULL |
+---------+------+--------+-------------+
SELECT 5 rows in set (... sec)
.. _window-functions-rank:
``rank()``
----------
.. _window-functions-rank-synopsis:
Synopsis
........
::
rank()
Returns the rank of every row within a partition of a result set.
Within each partition, the rank of the first row is ``1``. Subsequent tied
rows are given the same rank, and the potential rank of the next row
is incremented. Because of this, ranks may not be sequential.
Example::
cr> SELECT
... name,
... department_id,
... salary,
... RANK() OVER (ORDER BY salary desc) as salary_rank
... FROM (VALUES
... ('Bobson Dugnutt', 1, 2000),
... ('Todd Bonzalez', 2, 2500),
... ('Jess Brewer', 1, 2500),
... ('Safwan Buchanan', 1, 1900),
... ('Hal Dodd', 1, 2500),
... ('Gillian Hawes', 2, 2000))
... as t (name, department_id, salary);
+-----------------+---------------+--------+-------------+
| name | department_id | salary | salary_rank |
+-----------------+---------------+--------+-------------+
| Todd Bonzalez | 2 | 2500 | 1 |
| Jess Brewer | 1 | 2500 | 1 |
| Hal Dodd | 1 | 2500 | 1 |
| Bobson Dugnutt | 1 | 2000 | 4 |
| Gillian Hawes | 2 | 2000 | 4 |
| Safwan Buchanan | 1 | 1900 | 6 |
+-----------------+---------------+--------+-------------+
SELECT 6 rows in set (... sec)
.. _window-functions-dense-rank:
``dense_rank()``
----------------
.. _window-functions-dense-rank-synopsis:
Synopsis
........
::
dense_rank()
Returns the rank of every row within a partition of a result set, similar to
``rank``. However, unlike ``rank``, ``dense_rank`` always returns sequential
rank values.
Within each partition, the rank of the first row is ``1``. Subsequent tied
rows are given the same rank.
Example::
cr> SELECT
... name,
... department_id,
... salary,
... DENSE_RANK() OVER (ORDER BY salary desc) as salary_rank
... FROM (VALUES
... ('Bobson Dugnutt', 1, 2000),
... ('Todd Bonzalez', 2, 2500),
... ('Jess Brewer', 1, 2500),
... ('Safwan Buchanan', 1, 1900),
... ('Hal Dodd', 1, 2500),
... ('Gillian Hawes', 2, 2000))
... as t (name, department_id, salary);
+-----------------+---------------+--------+-------------+
| name | department_id | salary | salary_rank |
+-----------------+---------------+--------+-------------+
| Todd Bonzalez | 2 | 2500 | 1 |
| Jess Brewer | 1 | 2500 | 1 |
| Hal Dodd | 1 | 2500 | 1 |
| Bobson Dugnutt | 1 | 2000 | 2 |
| Gillian Hawes | 2 | 2000 | 2 |
| Safwan Buchanan | 1 | 1900 | 3 |
+-----------------+---------------+--------+-------------+
SELECT 6 rows in set (... sec)
.. _window-aggregate-functions:
Aggregate window functions
==========================
See :ref:`aggregation`.