summaryrefslogtreecommitdiffstats
path: root/src/test/regress/expected/aggregates.out
blob: 26031bc780037858f2657e4a383ebe0a5c5f1e88 (plain)
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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
--
-- AGGREGATES
--
-- directory paths are passed to us in environment variables
\getenv abs_srcdir PG_ABS_SRCDIR
-- avoid bit-exact output here because operations may not be bit-exact.
SET extra_float_digits = 0;
-- prepare some test data
CREATE TABLE aggtest (
	a 			int2,
	b			float4
);
\set filename :abs_srcdir '/data/agg.data'
COPY aggtest FROM :'filename';
ANALYZE aggtest;
SELECT avg(four) AS avg_1 FROM onek;
       avg_1        
--------------------
 1.5000000000000000
(1 row)

SELECT avg(a) AS avg_32 FROM aggtest WHERE a < 100;
       avg_32        
---------------------
 32.6666666666666667
(1 row)

-- In 7.1, avg(float4) is computed using float8 arithmetic.
-- Round the result to 3 digits to avoid platform-specific results.
SELECT avg(b)::numeric(10,3) AS avg_107_943 FROM aggtest;
 avg_107_943 
-------------
     107.943
(1 row)

SELECT avg(gpa) AS avg_3_4 FROM ONLY student;
 avg_3_4 
---------
     3.4
(1 row)

SELECT sum(four) AS sum_1500 FROM onek;
 sum_1500 
----------
     1500
(1 row)

SELECT sum(a) AS sum_198 FROM aggtest;
 sum_198 
---------
     198
(1 row)

SELECT sum(b) AS avg_431_773 FROM aggtest;
 avg_431_773 
-------------
     431.773
(1 row)

SELECT sum(gpa) AS avg_6_8 FROM ONLY student;
 avg_6_8 
---------
     6.8
(1 row)

SELECT max(four) AS max_3 FROM onek;
 max_3 
-------
     3
(1 row)

SELECT max(a) AS max_100 FROM aggtest;
 max_100 
---------
     100
(1 row)

SELECT max(aggtest.b) AS max_324_78 FROM aggtest;
 max_324_78 
------------
     324.78
(1 row)

SELECT max(student.gpa) AS max_3_7 FROM student;
 max_3_7 
---------
     3.7
(1 row)

SELECT stddev_pop(b) FROM aggtest;
   stddev_pop    
-----------------
 131.10703231895
(1 row)

SELECT stddev_samp(b) FROM aggtest;
   stddev_samp    
------------------
 151.389360803998
(1 row)

SELECT var_pop(b) FROM aggtest;
     var_pop      
------------------
 17189.0539234823
(1 row)

SELECT var_samp(b) FROM aggtest;
     var_samp     
------------------
 22918.7385646431
(1 row)

SELECT stddev_pop(b::numeric) FROM aggtest;
    stddev_pop    
------------------
 131.107032862199
(1 row)

SELECT stddev_samp(b::numeric) FROM aggtest;
   stddev_samp    
------------------
 151.389361431288
(1 row)

SELECT var_pop(b::numeric) FROM aggtest;
      var_pop       
--------------------
 17189.054065929769
(1 row)

SELECT var_samp(b::numeric) FROM aggtest;
      var_samp      
--------------------
 22918.738754573025
(1 row)

-- population variance is defined for a single tuple, sample variance
-- is not
SELECT var_pop(1.0::float8), var_samp(2.0::float8);
 var_pop | var_samp 
---------+----------
       0 |         
(1 row)

SELECT stddev_pop(3.0::float8), stddev_samp(4.0::float8);
 stddev_pop | stddev_samp 
------------+-------------
          0 |            
(1 row)

SELECT var_pop('inf'::float8), var_samp('inf'::float8);
 var_pop | var_samp 
---------+----------
     NaN |         
(1 row)

SELECT stddev_pop('inf'::float8), stddev_samp('inf'::float8);
 stddev_pop | stddev_samp 
------------+-------------
        NaN |            
(1 row)

SELECT var_pop('nan'::float8), var_samp('nan'::float8);
 var_pop | var_samp 
---------+----------
     NaN |         
(1 row)

SELECT stddev_pop('nan'::float8), stddev_samp('nan'::float8);
 stddev_pop | stddev_samp 
------------+-------------
        NaN |            
(1 row)

SELECT var_pop(1.0::float4), var_samp(2.0::float4);
 var_pop | var_samp 
---------+----------
       0 |         
(1 row)

SELECT stddev_pop(3.0::float4), stddev_samp(4.0::float4);
 stddev_pop | stddev_samp 
------------+-------------
          0 |            
(1 row)

SELECT var_pop('inf'::float4), var_samp('inf'::float4);
 var_pop | var_samp 
---------+----------
     NaN |         
(1 row)

SELECT stddev_pop('inf'::float4), stddev_samp('inf'::float4);
 stddev_pop | stddev_samp 
------------+-------------
        NaN |            
(1 row)

SELECT var_pop('nan'::float4), var_samp('nan'::float4);
 var_pop | var_samp 
---------+----------
     NaN |         
(1 row)

SELECT stddev_pop('nan'::float4), stddev_samp('nan'::float4);
 stddev_pop | stddev_samp 
------------+-------------
        NaN |            
(1 row)

SELECT var_pop(1.0::numeric), var_samp(2.0::numeric);
 var_pop | var_samp 
---------+----------
       0 |         
(1 row)

SELECT stddev_pop(3.0::numeric), stddev_samp(4.0::numeric);
 stddev_pop | stddev_samp 
------------+-------------
          0 |            
(1 row)

SELECT var_pop('inf'::numeric), var_samp('inf'::numeric);
 var_pop | var_samp 
---------+----------
     NaN |         
(1 row)

SELECT stddev_pop('inf'::numeric), stddev_samp('inf'::numeric);
 stddev_pop | stddev_samp 
------------+-------------
        NaN |            
(1 row)

SELECT var_pop('nan'::numeric), var_samp('nan'::numeric);
 var_pop | var_samp 
---------+----------
     NaN |         
(1 row)

SELECT stddev_pop('nan'::numeric), stddev_samp('nan'::numeric);
 stddev_pop | stddev_samp 
------------+-------------
        NaN |            
(1 row)

-- verify correct results for null and NaN inputs
select sum(null::int4) from generate_series(1,3);
 sum 
-----
    
(1 row)

select sum(null::int8) from generate_series(1,3);
 sum 
-----
    
(1 row)

select sum(null::numeric) from generate_series(1,3);
 sum 
-----
    
(1 row)

select sum(null::float8) from generate_series(1,3);
 sum 
-----
    
(1 row)

select avg(null::int4) from generate_series(1,3);
 avg 
-----
    
(1 row)

select avg(null::int8) from generate_series(1,3);
 avg 
-----
    
(1 row)

select avg(null::numeric) from generate_series(1,3);
 avg 
-----
    
(1 row)

select avg(null::float8) from generate_series(1,3);
 avg 
-----
    
(1 row)

select sum('NaN'::numeric) from generate_series(1,3);
 sum 
-----
 NaN
(1 row)

select avg('NaN'::numeric) from generate_series(1,3);
 avg 
-----
 NaN
(1 row)

-- verify correct results for infinite inputs
SELECT sum(x::float8), avg(x::float8), var_pop(x::float8)
FROM (VALUES ('1'), ('infinity')) v(x);
   sum    |   avg    | var_pop 
----------+----------+---------
 Infinity | Infinity |     NaN
(1 row)

SELECT sum(x::float8), avg(x::float8), var_pop(x::float8)
FROM (VALUES ('infinity'), ('1')) v(x);
   sum    |   avg    | var_pop 
----------+----------+---------
 Infinity | Infinity |     NaN
(1 row)

SELECT sum(x::float8), avg(x::float8), var_pop(x::float8)
FROM (VALUES ('infinity'), ('infinity')) v(x);
   sum    |   avg    | var_pop 
----------+----------+---------
 Infinity | Infinity |     NaN
(1 row)

SELECT sum(x::float8), avg(x::float8), var_pop(x::float8)
FROM (VALUES ('-infinity'), ('infinity')) v(x);
 sum | avg | var_pop 
-----+-----+---------
 NaN | NaN |     NaN
(1 row)

SELECT sum(x::float8), avg(x::float8), var_pop(x::float8)
FROM (VALUES ('-infinity'), ('-infinity')) v(x);
    sum    |    avg    | var_pop 
-----------+-----------+---------
 -Infinity | -Infinity |     NaN
(1 row)

SELECT sum(x::numeric), avg(x::numeric), var_pop(x::numeric)
FROM (VALUES ('1'), ('infinity')) v(x);
   sum    |   avg    | var_pop 
----------+----------+---------
 Infinity | Infinity |     NaN
(1 row)

SELECT sum(x::numeric), avg(x::numeric), var_pop(x::numeric)
FROM (VALUES ('infinity'), ('1')) v(x);
   sum    |   avg    | var_pop 
----------+----------+---------
 Infinity | Infinity |     NaN
(1 row)

SELECT sum(x::numeric), avg(x::numeric), var_pop(x::numeric)
FROM (VALUES ('infinity'), ('infinity')) v(x);
   sum    |   avg    | var_pop 
----------+----------+---------
 Infinity | Infinity |     NaN
(1 row)

SELECT sum(x::numeric), avg(x::numeric), var_pop(x::numeric)
FROM (VALUES ('-infinity'), ('infinity')) v(x);
 sum | avg | var_pop 
-----+-----+---------
 NaN | NaN |     NaN
(1 row)

SELECT sum(x::numeric), avg(x::numeric), var_pop(x::numeric)
FROM (VALUES ('-infinity'), ('-infinity')) v(x);
    sum    |    avg    | var_pop 
-----------+-----------+---------
 -Infinity | -Infinity |     NaN
(1 row)

-- test accuracy with a large input offset
SELECT avg(x::float8), var_pop(x::float8)
FROM (VALUES (100000003), (100000004), (100000006), (100000007)) v(x);
    avg    | var_pop 
-----------+---------
 100000005 |     2.5
(1 row)

SELECT avg(x::float8), var_pop(x::float8)
FROM (VALUES (7000000000005), (7000000000007)) v(x);
      avg      | var_pop 
---------------+---------
 7000000000006 |       1
(1 row)

-- SQL2003 binary aggregates
SELECT regr_count(b, a) FROM aggtest;
 regr_count 
------------
          4
(1 row)

SELECT regr_sxx(b, a) FROM aggtest;
 regr_sxx 
----------
     5099
(1 row)

SELECT regr_syy(b, a) FROM aggtest;
     regr_syy     
------------------
 68756.2156939293
(1 row)

SELECT regr_sxy(b, a) FROM aggtest;
     regr_sxy     
------------------
 2614.51582155004
(1 row)

SELECT regr_avgx(b, a), regr_avgy(b, a) FROM aggtest;
 regr_avgx |    regr_avgy     
-----------+------------------
      49.5 | 107.943152273074
(1 row)

SELECT regr_r2(b, a) FROM aggtest;
      regr_r2       
--------------------
 0.0194977982031803
(1 row)

SELECT regr_slope(b, a), regr_intercept(b, a) FROM aggtest;
    regr_slope     |  regr_intercept  
-------------------+------------------
 0.512750700441271 | 82.5619926012309
(1 row)

SELECT covar_pop(b, a), covar_samp(b, a) FROM aggtest;
    covar_pop    |    covar_samp    
-----------------+------------------
 653.62895538751 | 871.505273850014
(1 row)

SELECT corr(b, a) FROM aggtest;
       corr        
-------------------
 0.139634516517873
(1 row)

-- check single-tuple behavior
SELECT covar_pop(1::float8,2::float8), covar_samp(3::float8,4::float8);
 covar_pop | covar_samp 
-----------+------------
         0 |           
(1 row)

SELECT covar_pop(1::float8,'inf'::float8), covar_samp(3::float8,'inf'::float8);
 covar_pop | covar_samp 
-----------+------------
       NaN |           
(1 row)

SELECT covar_pop(1::float8,'nan'::float8), covar_samp(3::float8,'nan'::float8);
 covar_pop | covar_samp 
-----------+------------
       NaN |           
(1 row)

-- test accum and combine functions directly
CREATE TABLE regr_test (x float8, y float8);
INSERT INTO regr_test VALUES (10,150),(20,250),(30,350),(80,540),(100,200);
SELECT count(*), sum(x), regr_sxx(y,x), sum(y),regr_syy(y,x), regr_sxy(y,x)
FROM regr_test WHERE x IN (10,20,30,80);
 count | sum | regr_sxx | sum  | regr_syy | regr_sxy 
-------+-----+----------+------+----------+----------
     4 | 140 |     2900 | 1290 |    83075 |    15050
(1 row)

SELECT count(*), sum(x), regr_sxx(y,x), sum(y),regr_syy(y,x), regr_sxy(y,x)
FROM regr_test;
 count | sum | regr_sxx | sum  | regr_syy | regr_sxy 
-------+-----+----------+------+----------+----------
     5 | 240 |     6280 | 1490 |    95080 |     8680
(1 row)

SELECT float8_accum('{4,140,2900}'::float8[], 100);
 float8_accum 
--------------
 {5,240,6280}
(1 row)

SELECT float8_regr_accum('{4,140,2900,1290,83075,15050}'::float8[], 200, 100);
      float8_regr_accum       
------------------------------
 {5,240,6280,1490,95080,8680}
(1 row)

SELECT count(*), sum(x), regr_sxx(y,x), sum(y),regr_syy(y,x), regr_sxy(y,x)
FROM regr_test WHERE x IN (10,20,30);
 count | sum | regr_sxx | sum | regr_syy | regr_sxy 
-------+-----+----------+-----+----------+----------
     3 |  60 |      200 | 750 |    20000 |     2000
(1 row)

SELECT count(*), sum(x), regr_sxx(y,x), sum(y),regr_syy(y,x), regr_sxy(y,x)
FROM regr_test WHERE x IN (80,100);
 count | sum | regr_sxx | sum | regr_syy | regr_sxy 
-------+-----+----------+-----+----------+----------
     2 | 180 |      200 | 740 |    57800 |    -3400
(1 row)

SELECT float8_combine('{3,60,200}'::float8[], '{0,0,0}'::float8[]);
 float8_combine 
----------------
 {3,60,200}
(1 row)

SELECT float8_combine('{0,0,0}'::float8[], '{2,180,200}'::float8[]);
 float8_combine 
----------------
 {2,180,200}
(1 row)

SELECT float8_combine('{3,60,200}'::float8[], '{2,180,200}'::float8[]);
 float8_combine 
----------------
 {5,240,6280}
(1 row)

SELECT float8_regr_combine('{3,60,200,750,20000,2000}'::float8[],
                           '{0,0,0,0,0,0}'::float8[]);
    float8_regr_combine    
---------------------------
 {3,60,200,750,20000,2000}
(1 row)

SELECT float8_regr_combine('{0,0,0,0,0,0}'::float8[],
                           '{2,180,200,740,57800,-3400}'::float8[]);
     float8_regr_combine     
-----------------------------
 {2,180,200,740,57800,-3400}
(1 row)

SELECT float8_regr_combine('{3,60,200,750,20000,2000}'::float8[],
                           '{2,180,200,740,57800,-3400}'::float8[]);
     float8_regr_combine      
------------------------------
 {5,240,6280,1490,95080,8680}
(1 row)

DROP TABLE regr_test;
-- test count, distinct
SELECT count(four) AS cnt_1000 FROM onek;
 cnt_1000 
----------
     1000
(1 row)

SELECT count(DISTINCT four) AS cnt_4 FROM onek;
 cnt_4 
-------
     4
(1 row)

select ten, count(*), sum(four) from onek
group by ten order by ten;
 ten | count | sum 
-----+-------+-----
   0 |   100 | 100
   1 |   100 | 200
   2 |   100 | 100
   3 |   100 | 200
   4 |   100 | 100
   5 |   100 | 200
   6 |   100 | 100
   7 |   100 | 200
   8 |   100 | 100
   9 |   100 | 200
(10 rows)

select ten, count(four), sum(DISTINCT four) from onek
group by ten order by ten;
 ten | count | sum 
-----+-------+-----
   0 |   100 |   2
   1 |   100 |   4
   2 |   100 |   2
   3 |   100 |   4
   4 |   100 |   2
   5 |   100 |   4
   6 |   100 |   2
   7 |   100 |   4
   8 |   100 |   2
   9 |   100 |   4
(10 rows)

-- user-defined aggregates
SELECT newavg(four) AS avg_1 FROM onek;
       avg_1        
--------------------
 1.5000000000000000
(1 row)

SELECT newsum(four) AS sum_1500 FROM onek;
 sum_1500 
----------
     1500
(1 row)

SELECT newcnt(four) AS cnt_1000 FROM onek;
 cnt_1000 
----------
     1000
(1 row)

SELECT newcnt(*) AS cnt_1000 FROM onek;
 cnt_1000 
----------
     1000
(1 row)

SELECT oldcnt(*) AS cnt_1000 FROM onek;
 cnt_1000 
----------
     1000
(1 row)

SELECT sum2(q1,q2) FROM int8_tbl;
       sum2        
-------------------
 18271560493827981
(1 row)

-- test for outer-level aggregates
-- this should work
select ten, sum(distinct four) from onek a
group by ten
having exists (select 1 from onek b where sum(distinct a.four) = b.four);
 ten | sum 
-----+-----
   0 |   2
   2 |   2
   4 |   2
   6 |   2
   8 |   2
(5 rows)

-- this should fail because subquery has an agg of its own in WHERE
select ten, sum(distinct four) from onek a
group by ten
having exists (select 1 from onek b
               where sum(distinct a.four + b.four) = b.four);
ERROR:  aggregate functions are not allowed in WHERE
LINE 4:                where sum(distinct a.four + b.four) = b.four)...
                             ^
-- Test handling of sublinks within outer-level aggregates.
-- Per bug report from Daniel Grace.
select
  (select max((select i.unique2 from tenk1 i where i.unique1 = o.unique1)))
from tenk1 o;
 max  
------
 9999
(1 row)

-- Test handling of Params within aggregate arguments in hashed aggregation.
-- Per bug report from Jeevan Chalke.
explain (verbose, costs off)
select s1, s2, sm
from generate_series(1, 3) s1,
     lateral (select s2, sum(s1 + s2) sm
              from generate_series(1, 3) s2 group by s2) ss
order by 1, 2;
                            QUERY PLAN                            
------------------------------------------------------------------
 Sort
   Output: s1.s1, s2.s2, (sum((s1.s1 + s2.s2)))
   Sort Key: s1.s1, s2.s2
   ->  Nested Loop
         Output: s1.s1, s2.s2, (sum((s1.s1 + s2.s2)))
         ->  Function Scan on pg_catalog.generate_series s1
               Output: s1.s1
               Function Call: generate_series(1, 3)
         ->  HashAggregate
               Output: s2.s2, sum((s1.s1 + s2.s2))
               Group Key: s2.s2
               ->  Function Scan on pg_catalog.generate_series s2
                     Output: s2.s2
                     Function Call: generate_series(1, 3)
(14 rows)

select s1, s2, sm
from generate_series(1, 3) s1,
     lateral (select s2, sum(s1 + s2) sm
              from generate_series(1, 3) s2 group by s2) ss
order by 1, 2;
 s1 | s2 | sm 
----+----+----
  1 |  1 |  2
  1 |  2 |  3
  1 |  3 |  4
  2 |  1 |  3
  2 |  2 |  4
  2 |  3 |  5
  3 |  1 |  4
  3 |  2 |  5
  3 |  3 |  6
(9 rows)

explain (verbose, costs off)
select array(select sum(x+y) s
            from generate_series(1,3) y group by y order by s)
  from generate_series(1,3) x;
                            QUERY PLAN                             
-------------------------------------------------------------------
 Function Scan on pg_catalog.generate_series x
   Output: (SubPlan 1)
   Function Call: generate_series(1, 3)
   SubPlan 1
     ->  Sort
           Output: (sum((x.x + y.y))), y.y
           Sort Key: (sum((x.x + y.y)))
           ->  HashAggregate
                 Output: sum((x.x + y.y)), y.y
                 Group Key: y.y
                 ->  Function Scan on pg_catalog.generate_series y
                       Output: y.y
                       Function Call: generate_series(1, 3)
(13 rows)

select array(select sum(x+y) s
            from generate_series(1,3) y group by y order by s)
  from generate_series(1,3) x;
  array  
---------
 {2,3,4}
 {3,4,5}
 {4,5,6}
(3 rows)

--
-- test for bitwise integer aggregates
--
CREATE TEMPORARY TABLE bitwise_test(
  i2 INT2,
  i4 INT4,
  i8 INT8,
  i INTEGER,
  x INT2,
  y BIT(4)
);
-- empty case
SELECT
  BIT_AND(i2) AS "?",
  BIT_OR(i4)  AS "?",
  BIT_XOR(i8) AS "?"
FROM bitwise_test;
 ? | ? | ? 
---+---+---
   |   |  
(1 row)

COPY bitwise_test FROM STDIN NULL 'null';
SELECT
  BIT_AND(i2) AS "1",
  BIT_AND(i4) AS "1",
  BIT_AND(i8) AS "1",
  BIT_AND(i)  AS "?",
  BIT_AND(x)  AS "0",
  BIT_AND(y)  AS "0100",
  BIT_OR(i2)  AS "7",
  BIT_OR(i4)  AS "7",
  BIT_OR(i8)  AS "7",
  BIT_OR(i)   AS "?",
  BIT_OR(x)   AS "7",
  BIT_OR(y)   AS "1101",
  BIT_XOR(i2) AS "5",
  BIT_XOR(i4) AS "5",
  BIT_XOR(i8) AS "5",
  BIT_XOR(i)  AS "?",
  BIT_XOR(x)  AS "7",
  BIT_XOR(y)  AS "1101"
FROM bitwise_test;
 1 | 1 | 1 | ? | 0 | 0100 | 7 | 7 | 7 | ? | 7 | 1101 | 5 | 5 | 5 | ? | 7 | 1101 
---+---+---+---+---+------+---+---+---+---+---+------+---+---+---+---+---+------
 1 | 1 | 1 | 1 | 0 | 0100 | 7 | 7 | 7 | 3 | 7 | 1101 | 5 | 5 | 5 | 2 | 7 | 1101
(1 row)

--
-- test boolean aggregates
--
-- first test all possible transition and final states
SELECT
  -- boolean and transitions
  -- null because strict
  booland_statefunc(NULL, NULL)  IS NULL AS "t",
  booland_statefunc(TRUE, NULL)  IS NULL AS "t",
  booland_statefunc(FALSE, NULL) IS NULL AS "t",
  booland_statefunc(NULL, TRUE)  IS NULL AS "t",
  booland_statefunc(NULL, FALSE) IS NULL AS "t",
  -- and actual computations
  booland_statefunc(TRUE, TRUE) AS "t",
  NOT booland_statefunc(TRUE, FALSE) AS "t",
  NOT booland_statefunc(FALSE, TRUE) AS "t",
  NOT booland_statefunc(FALSE, FALSE) AS "t";
 t | t | t | t | t | t | t | t | t 
---+---+---+---+---+---+---+---+---
 t | t | t | t | t | t | t | t | t
(1 row)

SELECT
  -- boolean or transitions
  -- null because strict
  boolor_statefunc(NULL, NULL)  IS NULL AS "t",
  boolor_statefunc(TRUE, NULL)  IS NULL AS "t",
  boolor_statefunc(FALSE, NULL) IS NULL AS "t",
  boolor_statefunc(NULL, TRUE)  IS NULL AS "t",
  boolor_statefunc(NULL, FALSE) IS NULL AS "t",
  -- actual computations
  boolor_statefunc(TRUE, TRUE) AS "t",
  boolor_statefunc(TRUE, FALSE) AS "t",
  boolor_statefunc(FALSE, TRUE) AS "t",
  NOT boolor_statefunc(FALSE, FALSE) AS "t";
 t | t | t | t | t | t | t | t | t 
---+---+---+---+---+---+---+---+---
 t | t | t | t | t | t | t | t | t
(1 row)

CREATE TEMPORARY TABLE bool_test(
  b1 BOOL,
  b2 BOOL,
  b3 BOOL,
  b4 BOOL);
-- empty case
SELECT
  BOOL_AND(b1)   AS "n",
  BOOL_OR(b3)    AS "n"
FROM bool_test;
 n | n 
---+---
   | 
(1 row)

COPY bool_test FROM STDIN NULL 'null';
SELECT
  BOOL_AND(b1)     AS "f",
  BOOL_AND(b2)     AS "t",
  BOOL_AND(b3)     AS "f",
  BOOL_AND(b4)     AS "n",
  BOOL_AND(NOT b2) AS "f",
  BOOL_AND(NOT b3) AS "t"
FROM bool_test;
 f | t | f | n | f | t 
---+---+---+---+---+---
 f | t | f |   | f | t
(1 row)

SELECT
  EVERY(b1)     AS "f",
  EVERY(b2)     AS "t",
  EVERY(b3)     AS "f",
  EVERY(b4)     AS "n",
  EVERY(NOT b2) AS "f",
  EVERY(NOT b3) AS "t"
FROM bool_test;
 f | t | f | n | f | t 
---+---+---+---+---+---
 f | t | f |   | f | t
(1 row)

SELECT
  BOOL_OR(b1)      AS "t",
  BOOL_OR(b2)      AS "t",
  BOOL_OR(b3)      AS "f",
  BOOL_OR(b4)      AS "n",
  BOOL_OR(NOT b2)  AS "f",
  BOOL_OR(NOT b3)  AS "t"
FROM bool_test;
 t | t | f | n | f | t 
---+---+---+---+---+---
 t | t | f |   | f | t
(1 row)

--
-- Test cases that should be optimized into indexscans instead of
-- the generic aggregate implementation.
--
-- Basic cases
explain (costs off)
  select min(unique1) from tenk1;
                         QUERY PLAN                         
------------------------------------------------------------
 Result
   InitPlan 1 (returns $0)
     ->  Limit
           ->  Index Only Scan using tenk1_unique1 on tenk1
                 Index Cond: (unique1 IS NOT NULL)
(5 rows)

select min(unique1) from tenk1;
 min 
-----
   0
(1 row)

explain (costs off)
  select max(unique1) from tenk1;
                             QUERY PLAN                              
---------------------------------------------------------------------
 Result
   InitPlan 1 (returns $0)
     ->  Limit
           ->  Index Only Scan Backward using tenk1_unique1 on tenk1
                 Index Cond: (unique1 IS NOT NULL)
(5 rows)

select max(unique1) from tenk1;
 max  
------
 9999
(1 row)

explain (costs off)
  select max(unique1) from tenk1 where unique1 < 42;
                               QUERY PLAN                               
------------------------------------------------------------------------
 Result
   InitPlan 1 (returns $0)
     ->  Limit
           ->  Index Only Scan Backward using tenk1_unique1 on tenk1
                 Index Cond: ((unique1 IS NOT NULL) AND (unique1 < 42))
(5 rows)

select max(unique1) from tenk1 where unique1 < 42;
 max 
-----
  41
(1 row)

explain (costs off)
  select max(unique1) from tenk1 where unique1 > 42;
                               QUERY PLAN                               
------------------------------------------------------------------------
 Result
   InitPlan 1 (returns $0)
     ->  Limit
           ->  Index Only Scan Backward using tenk1_unique1 on tenk1
                 Index Cond: ((unique1 IS NOT NULL) AND (unique1 > 42))
(5 rows)

select max(unique1) from tenk1 where unique1 > 42;
 max  
------
 9999
(1 row)

-- the planner may choose a generic aggregate here if parallel query is
-- enabled, since that plan will be parallel safe and the "optimized"
-- plan, which has almost identical cost, will not be.  we want to test
-- the optimized plan, so temporarily disable parallel query.
begin;
set local max_parallel_workers_per_gather = 0;
explain (costs off)
  select max(unique1) from tenk1 where unique1 > 42000;
                                QUERY PLAN                                 
---------------------------------------------------------------------------
 Result
   InitPlan 1 (returns $0)
     ->  Limit
           ->  Index Only Scan Backward using tenk1_unique1 on tenk1
                 Index Cond: ((unique1 IS NOT NULL) AND (unique1 > 42000))
(5 rows)

select max(unique1) from tenk1 where unique1 > 42000;
 max 
-----
    
(1 row)

rollback;
-- multi-column index (uses tenk1_thous_tenthous)
explain (costs off)
  select max(tenthous) from tenk1 where thousand = 33;
                                 QUERY PLAN                                 
----------------------------------------------------------------------------
 Result
   InitPlan 1 (returns $0)
     ->  Limit
           ->  Index Only Scan Backward using tenk1_thous_tenthous on tenk1
                 Index Cond: ((thousand = 33) AND (tenthous IS NOT NULL))
(5 rows)

select max(tenthous) from tenk1 where thousand = 33;
 max  
------
 9033
(1 row)

explain (costs off)
  select min(tenthous) from tenk1 where thousand = 33;
                                QUERY PLAN                                
--------------------------------------------------------------------------
 Result
   InitPlan 1 (returns $0)
     ->  Limit
           ->  Index Only Scan using tenk1_thous_tenthous on tenk1
                 Index Cond: ((thousand = 33) AND (tenthous IS NOT NULL))
(5 rows)

select min(tenthous) from tenk1 where thousand = 33;
 min 
-----
  33
(1 row)

-- check parameter propagation into an indexscan subquery
explain (costs off)
  select f1, (select min(unique1) from tenk1 where unique1 > f1) AS gt
    from int4_tbl;
                                       QUERY PLAN                                        
-----------------------------------------------------------------------------------------
 Seq Scan on int4_tbl
   SubPlan 2
     ->  Result
           InitPlan 1 (returns $1)
             ->  Limit
                   ->  Index Only Scan using tenk1_unique1 on tenk1
                         Index Cond: ((unique1 IS NOT NULL) AND (unique1 > int4_tbl.f1))
(7 rows)

select f1, (select min(unique1) from tenk1 where unique1 > f1) AS gt
  from int4_tbl;
     f1      | gt 
-------------+----
           0 |  1
      123456 |   
     -123456 |  0
  2147483647 |   
 -2147483647 |  0
(5 rows)

-- check some cases that were handled incorrectly in 8.3.0
explain (costs off)
  select distinct max(unique2) from tenk1;
                             QUERY PLAN                              
---------------------------------------------------------------------
 HashAggregate
   Group Key: $0
   InitPlan 1 (returns $0)
     ->  Limit
           ->  Index Only Scan Backward using tenk1_unique2 on tenk1
                 Index Cond: (unique2 IS NOT NULL)
   ->  Result
(7 rows)

select distinct max(unique2) from tenk1;
 max  
------
 9999
(1 row)

explain (costs off)
  select max(unique2) from tenk1 order by 1;
                             QUERY PLAN                              
---------------------------------------------------------------------
 Sort
   Sort Key: ($0)
   InitPlan 1 (returns $0)
     ->  Limit
           ->  Index Only Scan Backward using tenk1_unique2 on tenk1
                 Index Cond: (unique2 IS NOT NULL)
   ->  Result
(7 rows)

select max(unique2) from tenk1 order by 1;
 max  
------
 9999
(1 row)

explain (costs off)
  select max(unique2) from tenk1 order by max(unique2);
                             QUERY PLAN                              
---------------------------------------------------------------------
 Sort
   Sort Key: ($0)
   InitPlan 1 (returns $0)
     ->  Limit
           ->  Index Only Scan Backward using tenk1_unique2 on tenk1
                 Index Cond: (unique2 IS NOT NULL)
   ->  Result
(7 rows)

select max(unique2) from tenk1 order by max(unique2);
 max  
------
 9999
(1 row)

explain (costs off)
  select max(unique2) from tenk1 order by max(unique2)+1;
                             QUERY PLAN                              
---------------------------------------------------------------------
 Sort
   Sort Key: (($0 + 1))
   InitPlan 1 (returns $0)
     ->  Limit
           ->  Index Only Scan Backward using tenk1_unique2 on tenk1
                 Index Cond: (unique2 IS NOT NULL)
   ->  Result
(7 rows)

select max(unique2) from tenk1 order by max(unique2)+1;
 max  
------
 9999
(1 row)

explain (costs off)
  select max(unique2), generate_series(1,3) as g from tenk1 order by g desc;
                             QUERY PLAN                              
---------------------------------------------------------------------
 Sort
   Sort Key: (generate_series(1, 3)) DESC
   InitPlan 1 (returns $0)
     ->  Limit
           ->  Index Only Scan Backward using tenk1_unique2 on tenk1
                 Index Cond: (unique2 IS NOT NULL)
   ->  ProjectSet
         ->  Result
(8 rows)

select max(unique2), generate_series(1,3) as g from tenk1 order by g desc;
 max  | g 
------+---
 9999 | 3
 9999 | 2
 9999 | 1
(3 rows)

-- interesting corner case: constant gets optimized into a seqscan
explain (costs off)
  select max(100) from tenk1;
                     QUERY PLAN                     
----------------------------------------------------
 Result
   InitPlan 1 (returns $0)
     ->  Limit
           ->  Result
                 One-Time Filter: (100 IS NOT NULL)
                 ->  Seq Scan on tenk1
(6 rows)

select max(100) from tenk1;
 max 
-----
 100
(1 row)

-- try it on an inheritance tree
create table minmaxtest(f1 int);
create table minmaxtest1() inherits (minmaxtest);
create table minmaxtest2() inherits (minmaxtest);
create table minmaxtest3() inherits (minmaxtest);
create index minmaxtesti on minmaxtest(f1);
create index minmaxtest1i on minmaxtest1(f1);
create index minmaxtest2i on minmaxtest2(f1 desc);
create index minmaxtest3i on minmaxtest3(f1) where f1 is not null;
insert into minmaxtest values(11), (12);
insert into minmaxtest1 values(13), (14);
insert into minmaxtest2 values(15), (16);
insert into minmaxtest3 values(17), (18);
explain (costs off)
  select min(f1), max(f1) from minmaxtest;
                                         QUERY PLAN                                          
---------------------------------------------------------------------------------------------
 Result
   InitPlan 1 (returns $0)
     ->  Limit
           ->  Merge Append
                 Sort Key: minmaxtest.f1
                 ->  Index Only Scan using minmaxtesti on minmaxtest minmaxtest_1
                       Index Cond: (f1 IS NOT NULL)
                 ->  Index Only Scan using minmaxtest1i on minmaxtest1 minmaxtest_2
                       Index Cond: (f1 IS NOT NULL)
                 ->  Index Only Scan Backward using minmaxtest2i on minmaxtest2 minmaxtest_3
                       Index Cond: (f1 IS NOT NULL)
                 ->  Index Only Scan using minmaxtest3i on minmaxtest3 minmaxtest_4
   InitPlan 2 (returns $1)
     ->  Limit
           ->  Merge Append
                 Sort Key: minmaxtest_5.f1 DESC
                 ->  Index Only Scan Backward using minmaxtesti on minmaxtest minmaxtest_6
                       Index Cond: (f1 IS NOT NULL)
                 ->  Index Only Scan Backward using minmaxtest1i on minmaxtest1 minmaxtest_7
                       Index Cond: (f1 IS NOT NULL)
                 ->  Index Only Scan using minmaxtest2i on minmaxtest2 minmaxtest_8
                       Index Cond: (f1 IS NOT NULL)
                 ->  Index Only Scan Backward using minmaxtest3i on minmaxtest3 minmaxtest_9
(23 rows)

select min(f1), max(f1) from minmaxtest;
 min | max 
-----+-----
  11 |  18
(1 row)

-- DISTINCT doesn't do anything useful here, but it shouldn't fail
explain (costs off)
  select distinct min(f1), max(f1) from minmaxtest;
                                         QUERY PLAN                                          
---------------------------------------------------------------------------------------------
 Unique
   InitPlan 1 (returns $0)
     ->  Limit
           ->  Merge Append
                 Sort Key: minmaxtest.f1
                 ->  Index Only Scan using minmaxtesti on minmaxtest minmaxtest_1
                       Index Cond: (f1 IS NOT NULL)
                 ->  Index Only Scan using minmaxtest1i on minmaxtest1 minmaxtest_2
                       Index Cond: (f1 IS NOT NULL)
                 ->  Index Only Scan Backward using minmaxtest2i on minmaxtest2 minmaxtest_3
                       Index Cond: (f1 IS NOT NULL)
                 ->  Index Only Scan using minmaxtest3i on minmaxtest3 minmaxtest_4
   InitPlan 2 (returns $1)
     ->  Limit
           ->  Merge Append
                 Sort Key: minmaxtest_5.f1 DESC
                 ->  Index Only Scan Backward using minmaxtesti on minmaxtest minmaxtest_6
                       Index Cond: (f1 IS NOT NULL)
                 ->  Index Only Scan Backward using minmaxtest1i on minmaxtest1 minmaxtest_7
                       Index Cond: (f1 IS NOT NULL)
                 ->  Index Only Scan using minmaxtest2i on minmaxtest2 minmaxtest_8
                       Index Cond: (f1 IS NOT NULL)
                 ->  Index Only Scan Backward using minmaxtest3i on minmaxtest3 minmaxtest_9
   ->  Sort
         Sort Key: ($0), ($1)
         ->  Result
(26 rows)

select distinct min(f1), max(f1) from minmaxtest;
 min | max 
-----+-----
  11 |  18
(1 row)

drop table minmaxtest cascade;
NOTICE:  drop cascades to 3 other objects
DETAIL:  drop cascades to table minmaxtest1
drop cascades to table minmaxtest2
drop cascades to table minmaxtest3
-- check for correct detection of nested-aggregate errors
select max(min(unique1)) from tenk1;
ERROR:  aggregate function calls cannot be nested
LINE 1: select max(min(unique1)) from tenk1;
                   ^
select (select max(min(unique1)) from int8_tbl) from tenk1;
ERROR:  aggregate function calls cannot be nested
LINE 1: select (select max(min(unique1)) from int8_tbl) from tenk1;
                           ^
select avg((select avg(a1.col1 order by (select avg(a2.col2) from tenk1 a3))
            from tenk1 a1(col1)))
from tenk1 a2(col2);
ERROR:  aggregate function calls cannot be nested
LINE 1: select avg((select avg(a1.col1 order by (select avg(a2.col2)...
                                                        ^
--
-- Test removal of redundant GROUP BY columns
--
create temp table t1 (a int, b int, c int, d int, primary key (a, b));
create temp table t2 (x int, y int, z int, primary key (x, y));
create temp table t3 (a int, b int, c int, primary key(a, b) deferrable);
-- Non-primary-key columns can be removed from GROUP BY
explain (costs off) select * from t1 group by a,b,c,d;
      QUERY PLAN      
----------------------
 HashAggregate
   Group Key: a, b
   ->  Seq Scan on t1
(3 rows)

-- No removal can happen if the complete PK is not present in GROUP BY
explain (costs off) select a,c from t1 group by a,c,d;
      QUERY PLAN      
----------------------
 HashAggregate
   Group Key: a, c, d
   ->  Seq Scan on t1
(3 rows)

-- Test removal across multiple relations
explain (costs off) select *
from t1 inner join t2 on t1.a = t2.x and t1.b = t2.y
group by t1.a,t1.b,t1.c,t1.d,t2.x,t2.y,t2.z;
                      QUERY PLAN                      
------------------------------------------------------
 HashAggregate
   Group Key: t1.a, t1.b, t2.x, t2.y
   ->  Hash Join
         Hash Cond: ((t2.x = t1.a) AND (t2.y = t1.b))
         ->  Seq Scan on t2
         ->  Hash
               ->  Seq Scan on t1
(7 rows)

-- Test case where t1 can be optimized but not t2
explain (costs off) select t1.*,t2.x,t2.z
from t1 inner join t2 on t1.a = t2.x and t1.b = t2.y
group by t1.a,t1.b,t1.c,t1.d,t2.x,t2.z;
                      QUERY PLAN                      
------------------------------------------------------
 HashAggregate
   Group Key: t1.a, t1.b, t2.x, t2.z
   ->  Hash Join
         Hash Cond: ((t2.x = t1.a) AND (t2.y = t1.b))
         ->  Seq Scan on t2
         ->  Hash
               ->  Seq Scan on t1
(7 rows)

-- Cannot optimize when PK is deferrable
explain (costs off) select * from t3 group by a,b,c;
      QUERY PLAN      
----------------------
 HashAggregate
   Group Key: a, b, c
   ->  Seq Scan on t3
(3 rows)

create temp table t1c () inherits (t1);
-- Ensure we don't remove any columns when t1 has a child table
explain (costs off) select * from t1 group by a,b,c,d;
             QUERY PLAN              
-------------------------------------
 HashAggregate
   Group Key: t1.a, t1.b, t1.c, t1.d
   ->  Append
         ->  Seq Scan on t1 t1_1
         ->  Seq Scan on t1c t1_2
(5 rows)

-- Okay to remove columns if we're only querying the parent.
explain (costs off) select * from only t1 group by a,b,c,d;
      QUERY PLAN      
----------------------
 HashAggregate
   Group Key: a, b
   ->  Seq Scan on t1
(3 rows)

create temp table p_t1 (
  a int,
  b int,
  c int,
  d int,
  primary key(a,b)
) partition by list(a);
create temp table p_t1_1 partition of p_t1 for values in(1);
create temp table p_t1_2 partition of p_t1 for values in(2);
-- Ensure we can remove non-PK columns for partitioned tables.
explain (costs off) select * from p_t1 group by a,b,c,d;
           QUERY PLAN           
--------------------------------
 HashAggregate
   Group Key: p_t1.a, p_t1.b
   ->  Append
         ->  Seq Scan on p_t1_1
         ->  Seq Scan on p_t1_2
(5 rows)

drop table t1 cascade;
NOTICE:  drop cascades to table t1c
drop table t2;
drop table t3;
drop table p_t1;
--
-- Test GROUP BY matching of join columns that are type-coerced due to USING
--
create temp table t1(f1 int, f2 bigint);
create temp table t2(f1 bigint, f22 bigint);
select f1 from t1 left join t2 using (f1) group by f1;
 f1 
----
(0 rows)

select f1 from t1 left join t2 using (f1) group by t1.f1;
 f1 
----
(0 rows)

select t1.f1 from t1 left join t2 using (f1) group by t1.f1;
 f1 
----
(0 rows)

-- only this one should fail:
select t1.f1 from t1 left join t2 using (f1) group by f1;
ERROR:  column "t1.f1" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: select t1.f1 from t1 left join t2 using (f1) group by f1;
               ^
drop table t1, t2;
--
-- Test combinations of DISTINCT and/or ORDER BY
--
select array_agg(a order by b)
  from (values (1,4),(2,3),(3,1),(4,2)) v(a,b);
 array_agg 
-----------
 {3,4,2,1}
(1 row)

select array_agg(a order by a)
  from (values (1,4),(2,3),(3,1),(4,2)) v(a,b);
 array_agg 
-----------
 {1,2,3,4}
(1 row)

select array_agg(a order by a desc)
  from (values (1,4),(2,3),(3,1),(4,2)) v(a,b);
 array_agg 
-----------
 {4,3,2,1}
(1 row)

select array_agg(b order by a desc)
  from (values (1,4),(2,3),(3,1),(4,2)) v(a,b);
 array_agg 
-----------
 {2,1,3,4}
(1 row)

select array_agg(distinct a)
  from (values (1),(2),(1),(3),(null),(2)) v(a);
  array_agg   
--------------
 {1,2,3,NULL}
(1 row)

select array_agg(distinct a order by a)
  from (values (1),(2),(1),(3),(null),(2)) v(a);
  array_agg   
--------------
 {1,2,3,NULL}
(1 row)

select array_agg(distinct a order by a desc)
  from (values (1),(2),(1),(3),(null),(2)) v(a);
  array_agg   
--------------
 {NULL,3,2,1}
(1 row)

select array_agg(distinct a order by a desc nulls last)
  from (values (1),(2),(1),(3),(null),(2)) v(a);
  array_agg   
--------------
 {3,2,1,NULL}
(1 row)

-- multi-arg aggs, strict/nonstrict, distinct/order by
select aggfstr(a,b,c)
  from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c);
                aggfstr                
---------------------------------------
 {"(1,3,foo)","(2,2,bar)","(3,1,baz)"}
(1 row)

select aggfns(a,b,c)
  from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c);
                    aggfns                     
-----------------------------------------------
 {"(1,3,foo)","(0,,)","(2,2,bar)","(3,1,baz)"}
(1 row)

select aggfstr(distinct a,b,c)
  from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c),
       generate_series(1,3) i;
                aggfstr                
---------------------------------------
 {"(1,3,foo)","(2,2,bar)","(3,1,baz)"}
(1 row)

select aggfns(distinct a,b,c)
  from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c),
       generate_series(1,3) i;
                    aggfns                     
-----------------------------------------------
 {"(0,,)","(1,3,foo)","(2,2,bar)","(3,1,baz)"}
(1 row)

select aggfstr(distinct a,b,c order by b)
  from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c),
       generate_series(1,3) i;
                aggfstr                
---------------------------------------
 {"(3,1,baz)","(2,2,bar)","(1,3,foo)"}
(1 row)

select aggfns(distinct a,b,c order by b)
  from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c),
       generate_series(1,3) i;
                    aggfns                     
-----------------------------------------------
 {"(3,1,baz)","(2,2,bar)","(1,3,foo)","(0,,)"}
(1 row)

-- test specific code paths
select aggfns(distinct a,a,c order by c using ~<~,a)
  from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c),
       generate_series(1,2) i;
                     aggfns                     
------------------------------------------------
 {"(2,2,bar)","(3,3,baz)","(1,1,foo)","(0,0,)"}
(1 row)

select aggfns(distinct a,a,c order by c using ~<~)
  from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c),
       generate_series(1,2) i;
                     aggfns                     
------------------------------------------------
 {"(2,2,bar)","(3,3,baz)","(1,1,foo)","(0,0,)"}
(1 row)

select aggfns(distinct a,a,c order by a)
  from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c),
       generate_series(1,2) i;
                     aggfns                     
------------------------------------------------
 {"(0,0,)","(1,1,foo)","(2,2,bar)","(3,3,baz)"}
(1 row)

select aggfns(distinct a,b,c order by a,c using ~<~,b)
  from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c),
       generate_series(1,2) i;
                    aggfns                     
-----------------------------------------------
 {"(0,,)","(1,3,foo)","(2,2,bar)","(3,1,baz)"}
(1 row)

-- check node I/O via view creation and usage, also deparsing logic
create view agg_view1 as
  select aggfns(a,b,c)
    from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c);
select * from agg_view1;
                    aggfns                     
-----------------------------------------------
 {"(1,3,foo)","(0,,)","(2,2,bar)","(3,1,baz)"}
(1 row)

select pg_get_viewdef('agg_view1'::regclass);
                                                   pg_get_viewdef                                                    
---------------------------------------------------------------------------------------------------------------------
  SELECT aggfns(v.a, v.b, v.c) AS aggfns                                                                            +
    FROM ( VALUES (1,3,'foo'::text), (0,NULL::integer,NULL::text), (2,2,'bar'::text), (3,1,'baz'::text)) v(a, b, c);
(1 row)

create or replace view agg_view1 as
  select aggfns(distinct a,b,c)
    from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c),
         generate_series(1,3) i;
select * from agg_view1;
                    aggfns                     
-----------------------------------------------
 {"(0,,)","(1,3,foo)","(2,2,bar)","(3,1,baz)"}
(1 row)

select pg_get_viewdef('agg_view1'::regclass);
                                                   pg_get_viewdef                                                    
---------------------------------------------------------------------------------------------------------------------
  SELECT aggfns(DISTINCT v.a, v.b, v.c) AS aggfns                                                                   +
    FROM ( VALUES (1,3,'foo'::text), (0,NULL::integer,NULL::text), (2,2,'bar'::text), (3,1,'baz'::text)) v(a, b, c),+
     generate_series(1, 3) i(i);
(1 row)

create or replace view agg_view1 as
  select aggfns(distinct a,b,c order by b)
    from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c),
         generate_series(1,3) i;
select * from agg_view1;
                    aggfns                     
-----------------------------------------------
 {"(3,1,baz)","(2,2,bar)","(1,3,foo)","(0,,)"}
(1 row)

select pg_get_viewdef('agg_view1'::regclass);
                                                   pg_get_viewdef                                                    
---------------------------------------------------------------------------------------------------------------------
  SELECT aggfns(DISTINCT v.a, v.b, v.c ORDER BY v.b) AS aggfns                                                      +
    FROM ( VALUES (1,3,'foo'::text), (0,NULL::integer,NULL::text), (2,2,'bar'::text), (3,1,'baz'::text)) v(a, b, c),+
     generate_series(1, 3) i(i);
(1 row)

create or replace view agg_view1 as
  select aggfns(a,b,c order by b+1)
    from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c);
select * from agg_view1;
                    aggfns                     
-----------------------------------------------
 {"(3,1,baz)","(2,2,bar)","(1,3,foo)","(0,,)"}
(1 row)

select pg_get_viewdef('agg_view1'::regclass);
                                                   pg_get_viewdef                                                    
---------------------------------------------------------------------------------------------------------------------
  SELECT aggfns(v.a, v.b, v.c ORDER BY (v.b + 1)) AS aggfns                                                         +
    FROM ( VALUES (1,3,'foo'::text), (0,NULL::integer,NULL::text), (2,2,'bar'::text), (3,1,'baz'::text)) v(a, b, c);
(1 row)

create or replace view agg_view1 as
  select aggfns(a,a,c order by b)
    from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c);
select * from agg_view1;
                     aggfns                     
------------------------------------------------
 {"(3,3,baz)","(2,2,bar)","(1,1,foo)","(0,0,)"}
(1 row)

select pg_get_viewdef('agg_view1'::regclass);
                                                   pg_get_viewdef                                                    
---------------------------------------------------------------------------------------------------------------------
  SELECT aggfns(v.a, v.a, v.c ORDER BY v.b) AS aggfns                                                               +
    FROM ( VALUES (1,3,'foo'::text), (0,NULL::integer,NULL::text), (2,2,'bar'::text), (3,1,'baz'::text)) v(a, b, c);
(1 row)

create or replace view agg_view1 as
  select aggfns(a,b,c order by c using ~<~)
    from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c);
select * from agg_view1;
                    aggfns                     
-----------------------------------------------
 {"(2,2,bar)","(3,1,baz)","(1,3,foo)","(0,,)"}
(1 row)

select pg_get_viewdef('agg_view1'::regclass);
                                                   pg_get_viewdef                                                    
---------------------------------------------------------------------------------------------------------------------
  SELECT aggfns(v.a, v.b, v.c ORDER BY v.c USING ~<~ NULLS LAST) AS aggfns                                          +
    FROM ( VALUES (1,3,'foo'::text), (0,NULL::integer,NULL::text), (2,2,'bar'::text), (3,1,'baz'::text)) v(a, b, c);
(1 row)

create or replace view agg_view1 as
  select aggfns(distinct a,b,c order by a,c using ~<~,b)
    from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c),
         generate_series(1,2) i;
select * from agg_view1;
                    aggfns                     
-----------------------------------------------
 {"(0,,)","(1,3,foo)","(2,2,bar)","(3,1,baz)"}
(1 row)

select pg_get_viewdef('agg_view1'::regclass);
                                                   pg_get_viewdef                                                    
---------------------------------------------------------------------------------------------------------------------
  SELECT aggfns(DISTINCT v.a, v.b, v.c ORDER BY v.a, v.c USING ~<~ NULLS LAST, v.b) AS aggfns                       +
    FROM ( VALUES (1,3,'foo'::text), (0,NULL::integer,NULL::text), (2,2,'bar'::text), (3,1,'baz'::text)) v(a, b, c),+
     generate_series(1, 2) i(i);
(1 row)

drop view agg_view1;
-- incorrect DISTINCT usage errors
select aggfns(distinct a,b,c order by i)
  from (values (1,1,'foo')) v(a,b,c), generate_series(1,2) i;
ERROR:  in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list
LINE 1: select aggfns(distinct a,b,c order by i)
                                              ^
select aggfns(distinct a,b,c order by a,b+1)
  from (values (1,1,'foo')) v(a,b,c), generate_series(1,2) i;
ERROR:  in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list
LINE 1: select aggfns(distinct a,b,c order by a,b+1)
                                                ^
select aggfns(distinct a,b,c order by a,b,i,c)
  from (values (1,1,'foo')) v(a,b,c), generate_series(1,2) i;
ERROR:  in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list
LINE 1: select aggfns(distinct a,b,c order by a,b,i,c)
                                                  ^
select aggfns(distinct a,a,c order by a,b)
  from (values (1,1,'foo')) v(a,b,c), generate_series(1,2) i;
ERROR:  in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list
LINE 1: select aggfns(distinct a,a,c order by a,b)
                                                ^
-- string_agg tests
select string_agg(a,',') from (values('aaaa'),('bbbb'),('cccc')) g(a);
   string_agg   
----------------
 aaaa,bbbb,cccc
(1 row)

select string_agg(a,',') from (values('aaaa'),(null),('bbbb'),('cccc')) g(a);
   string_agg   
----------------
 aaaa,bbbb,cccc
(1 row)

select string_agg(a,'AB') from (values(null),(null),('bbbb'),('cccc')) g(a);
 string_agg 
------------
 bbbbABcccc
(1 row)

select string_agg(a,',') from (values(null),(null)) g(a);
 string_agg 
------------
 
(1 row)

-- check some implicit casting cases, as per bug #5564
select string_agg(distinct f1, ',' order by f1) from varchar_tbl;  -- ok
 string_agg 
------------
 a,ab,abcd
(1 row)

select string_agg(distinct f1::text, ',' order by f1) from varchar_tbl;  -- not ok
ERROR:  in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list
LINE 1: select string_agg(distinct f1::text, ',' order by f1) from v...
                                                          ^
select string_agg(distinct f1, ',' order by f1::text) from varchar_tbl;  -- not ok
ERROR:  in an aggregate with DISTINCT, ORDER BY expressions must appear in argument list
LINE 1: select string_agg(distinct f1, ',' order by f1::text) from v...
                                                    ^
select string_agg(distinct f1::text, ',' order by f1::text) from varchar_tbl;  -- ok
 string_agg 
------------
 a,ab,abcd
(1 row)

-- string_agg bytea tests
create table bytea_test_table(v bytea);
select string_agg(v, '') from bytea_test_table;
 string_agg 
------------
 
(1 row)

insert into bytea_test_table values(decode('ff','hex'));
select string_agg(v, '') from bytea_test_table;
 string_agg 
------------
 \xff
(1 row)

insert into bytea_test_table values(decode('aa','hex'));
select string_agg(v, '') from bytea_test_table;
 string_agg 
------------
 \xffaa
(1 row)

select string_agg(v, NULL) from bytea_test_table;
 string_agg 
------------
 \xffaa
(1 row)

select string_agg(v, decode('ee', 'hex')) from bytea_test_table;
 string_agg 
------------
 \xffeeaa
(1 row)

drop table bytea_test_table;
-- FILTER tests
select min(unique1) filter (where unique1 > 100) from tenk1;
 min 
-----
 101
(1 row)

select sum(1/ten) filter (where ten > 0) from tenk1;
 sum  
------
 1000
(1 row)

select ten, sum(distinct four) filter (where four::text ~ '123') from onek a
group by ten;
 ten | sum 
-----+-----
   0 |    
   1 |    
   2 |    
   3 |    
   4 |    
   5 |    
   6 |    
   7 |    
   8 |    
   9 |    
(10 rows)

select ten, sum(distinct four) filter (where four > 10) from onek a
group by ten
having exists (select 1 from onek b where sum(distinct a.four) = b.four);
 ten | sum 
-----+-----
   0 |    
   2 |    
   4 |    
   6 |    
   8 |    
(5 rows)

select max(foo COLLATE "C") filter (where (bar collate "POSIX") > '0')
from (values ('a', 'b')) AS v(foo,bar);
 max 
-----
 a
(1 row)

-- outer reference in FILTER (PostgreSQL extension)
select (select count(*)
        from (values (1)) t0(inner_c))
from (values (2),(3)) t1(outer_c); -- inner query is aggregation query
 count 
-------
     1
     1
(2 rows)

select (select count(*) filter (where outer_c <> 0)
        from (values (1)) t0(inner_c))
from (values (2),(3)) t1(outer_c); -- outer query is aggregation query
 count 
-------
     2
(1 row)

select (select count(inner_c) filter (where outer_c <> 0)
        from (values (1)) t0(inner_c))
from (values (2),(3)) t1(outer_c); -- inner query is aggregation query
 count 
-------
     1
     1
(2 rows)

select
  (select max((select i.unique2 from tenk1 i where i.unique1 = o.unique1))
     filter (where o.unique1 < 10))
from tenk1 o;					-- outer query is aggregation query
 max  
------
 9998
(1 row)

-- subquery in FILTER clause (PostgreSQL extension)
select sum(unique1) FILTER (WHERE
  unique1 IN (SELECT unique1 FROM onek where unique1 < 100)) FROM tenk1;
 sum  
------
 4950
(1 row)

-- exercise lots of aggregate parts with FILTER
select aggfns(distinct a,b,c order by a,c using ~<~,b) filter (where a > 1)
    from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c),
    generate_series(1,2) i;
          aggfns           
---------------------------
 {"(2,2,bar)","(3,1,baz)"}
(1 row)

-- check handling of bare boolean Var in FILTER
select max(0) filter (where b1) from bool_test;
 max 
-----
   0
(1 row)

select (select max(0) filter (where b1)) from bool_test;
 max 
-----
   0
(1 row)

-- check for correct detection of nested-aggregate errors in FILTER
select max(unique1) filter (where sum(ten) > 0) from tenk1;
ERROR:  aggregate functions are not allowed in FILTER
LINE 1: select max(unique1) filter (where sum(ten) > 0) from tenk1;
                                          ^
select (select max(unique1) filter (where sum(ten) > 0) from int8_tbl) from tenk1;
ERROR:  aggregate function calls cannot be nested
LINE 1: select (select max(unique1) filter (where sum(ten) > 0) from...
                                                  ^
select max(unique1) filter (where bool_or(ten > 0)) from tenk1;
ERROR:  aggregate functions are not allowed in FILTER
LINE 1: select max(unique1) filter (where bool_or(ten > 0)) from ten...
                                          ^
select (select max(unique1) filter (where bool_or(ten > 0)) from int8_tbl) from tenk1;
ERROR:  aggregate function calls cannot be nested
LINE 1: select (select max(unique1) filter (where bool_or(ten > 0)) ...
                                                  ^
-- ordered-set aggregates
select p, percentile_cont(p) within group (order by x::float8)
from generate_series(1,5) x,
     (values (0::float8),(0.1),(0.25),(0.4),(0.5),(0.6),(0.75),(0.9),(1)) v(p)
group by p order by p;
  p   | percentile_cont 
------+-----------------
    0 |               1
  0.1 |             1.4
 0.25 |               2
  0.4 |             2.6
  0.5 |               3
  0.6 |             3.4
 0.75 |               4
  0.9 |             4.6
    1 |               5
(9 rows)

select p, percentile_cont(p order by p) within group (order by x)  -- error
from generate_series(1,5) x,
     (values (0::float8),(0.1),(0.25),(0.4),(0.5),(0.6),(0.75),(0.9),(1)) v(p)
group by p order by p;
ERROR:  cannot use multiple ORDER BY clauses with WITHIN GROUP
LINE 1: select p, percentile_cont(p order by p) within group (order ...
                                                ^
select p, sum() within group (order by x::float8)  -- error
from generate_series(1,5) x,
     (values (0::float8),(0.1),(0.25),(0.4),(0.5),(0.6),(0.75),(0.9),(1)) v(p)
group by p order by p;
ERROR:  sum is not an ordered-set aggregate, so it cannot have WITHIN GROUP
LINE 1: select p, sum() within group (order by x::float8)  -- error
                  ^
select p, percentile_cont(p,p)  -- error
from generate_series(1,5) x,
     (values (0::float8),(0.1),(0.25),(0.4),(0.5),(0.6),(0.75),(0.9),(1)) v(p)
group by p order by p;
ERROR:  WITHIN GROUP is required for ordered-set aggregate percentile_cont
LINE 1: select p, percentile_cont(p,p)  -- error
                  ^
select percentile_cont(0.5) within group (order by b) from aggtest;
 percentile_cont  
------------------
 53.4485001564026
(1 row)

select percentile_cont(0.5) within group (order by b), sum(b) from aggtest;
 percentile_cont  |   sum   
------------------+---------
 53.4485001564026 | 431.773
(1 row)

select percentile_cont(0.5) within group (order by thousand) from tenk1;
 percentile_cont 
-----------------
           499.5
(1 row)

select percentile_disc(0.5) within group (order by thousand) from tenk1;
 percentile_disc 
-----------------
             499
(1 row)

select rank(3) within group (order by x)
from (values (1),(1),(2),(2),(3),(3),(4)) v(x);
 rank 
------
    5
(1 row)

select cume_dist(3) within group (order by x)
from (values (1),(1),(2),(2),(3),(3),(4)) v(x);
 cume_dist 
-----------
     0.875
(1 row)

select percent_rank(3) within group (order by x)
from (values (1),(1),(2),(2),(3),(3),(4),(5)) v(x);
 percent_rank 
--------------
          0.5
(1 row)

select dense_rank(3) within group (order by x)
from (values (1),(1),(2),(2),(3),(3),(4)) v(x);
 dense_rank 
------------
          3
(1 row)

select percentile_disc(array[0,0.1,0.25,0.5,0.75,0.9,1]) within group (order by thousand)
from tenk1;
      percentile_disc       
----------------------------
 {0,99,249,499,749,899,999}
(1 row)

select percentile_cont(array[0,0.25,0.5,0.75,1]) within group (order by thousand)
from tenk1;
       percentile_cont       
-----------------------------
 {0,249.75,499.5,749.25,999}
(1 row)

select percentile_disc(array[[null,1,0.5],[0.75,0.25,null]]) within group (order by thousand)
from tenk1;
         percentile_disc         
---------------------------------
 {{NULL,999,499},{749,249,NULL}}
(1 row)

select percentile_cont(array[0,1,0.25,0.75,0.5,1,0.3,0.32,0.35,0.38,0.4]) within group (order by x)
from generate_series(1,6) x;
             percentile_cont              
------------------------------------------
 {1,6,2.25,4.75,3.5,6,2.5,2.6,2.75,2.9,3}
(1 row)

select ten, mode() within group (order by string4) from tenk1 group by ten;
 ten |  mode  
-----+--------
   0 | HHHHxx
   1 | OOOOxx
   2 | VVVVxx
   3 | OOOOxx
   4 | HHHHxx
   5 | HHHHxx
   6 | OOOOxx
   7 | AAAAxx
   8 | VVVVxx
   9 | VVVVxx
(10 rows)

select percentile_disc(array[0.25,0.5,0.75]) within group (order by x)
from unnest('{fred,jim,fred,jack,jill,fred,jill,jim,jim,sheila,jim,sheila}'::text[]) u(x);
 percentile_disc 
-----------------
 {fred,jill,jim}
(1 row)

-- check collation propagates up in suitable cases:
select pg_collation_for(percentile_disc(1) within group (order by x collate "POSIX"))
  from (values ('fred'),('jim')) v(x);
 pg_collation_for 
------------------
 "POSIX"
(1 row)

-- ordered-set aggs created with CREATE AGGREGATE
select test_rank(3) within group (order by x)
from (values (1),(1),(2),(2),(3),(3),(4)) v(x);
 test_rank 
-----------
         5
(1 row)

select test_percentile_disc(0.5) within group (order by thousand) from tenk1;
 test_percentile_disc 
----------------------
                  499
(1 row)

-- ordered-set aggs can't use ungrouped vars in direct args:
select rank(x) within group (order by x) from generate_series(1,5) x;
ERROR:  column "x.x" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: select rank(x) within group (order by x) from generate_serie...
                    ^
DETAIL:  Direct arguments of an ordered-set aggregate must use only grouped columns.
-- outer-level agg can't use a grouped arg of a lower level, either:
select array(select percentile_disc(a) within group (order by x)
               from (values (0.3),(0.7)) v(a) group by a)
  from generate_series(1,5) g(x);
ERROR:  outer-level aggregate cannot contain a lower-level variable in its direct arguments
LINE 1: select array(select percentile_disc(a) within group (order b...
                                            ^
-- agg in the direct args is a grouping violation, too:
select rank(sum(x)) within group (order by x) from generate_series(1,5) x;
ERROR:  aggregate function calls cannot be nested
LINE 1: select rank(sum(x)) within group (order by x) from generate_...
                    ^
-- hypothetical-set type unification and argument-count failures:
select rank(3) within group (order by x) from (values ('fred'),('jim')) v(x);
ERROR:  WITHIN GROUP types text and integer cannot be matched
LINE 1: select rank(3) within group (order by x) from (values ('fred...
                    ^
select rank(3) within group (order by stringu1,stringu2) from tenk1;
ERROR:  function rank(integer, name, name) does not exist
LINE 1: select rank(3) within group (order by stringu1,stringu2) fro...
               ^
HINT:  To use the hypothetical-set aggregate rank, the number of hypothetical direct arguments (here 1) must match the number of ordering columns (here 2).
select rank('fred') within group (order by x) from generate_series(1,5) x;
ERROR:  invalid input syntax for type integer: "fred"
LINE 1: select rank('fred') within group (order by x) from generate_...
                    ^
select rank('adam'::text collate "C") within group (order by x collate "POSIX")
  from (values ('fred'),('jim')) v(x);
ERROR:  collation mismatch between explicit collations "C" and "POSIX"
LINE 1: ...adam'::text collate "C") within group (order by x collate "P...
                                                             ^
-- hypothetical-set type unification successes:
select rank('adam'::varchar) within group (order by x) from (values ('fred'),('jim')) v(x);
 rank 
------
    1
(1 row)

select rank('3') within group (order by x) from generate_series(1,5) x;
 rank 
------
    3
(1 row)

-- divide by zero check
select percent_rank(0) within group (order by x) from generate_series(1,0) x;
 percent_rank 
--------------
            0
(1 row)

-- deparse and multiple features:
create view aggordview1 as
select ten,
       percentile_disc(0.5) within group (order by thousand) as p50,
       percentile_disc(0.5) within group (order by thousand) filter (where hundred=1) as px,
       rank(5,'AZZZZ',50) within group (order by hundred, string4 desc, hundred)
  from tenk1
 group by ten order by ten;
select pg_get_viewdef('aggordview1');
                                                        pg_get_viewdef                                                         
-------------------------------------------------------------------------------------------------------------------------------
  SELECT tenk1.ten,                                                                                                           +
     percentile_disc((0.5)::double precision) WITHIN GROUP (ORDER BY tenk1.thousand) AS p50,                                  +
     percentile_disc((0.5)::double precision) WITHIN GROUP (ORDER BY tenk1.thousand) FILTER (WHERE (tenk1.hundred = 1)) AS px,+
     rank(5, 'AZZZZ'::name, 50) WITHIN GROUP (ORDER BY tenk1.hundred, tenk1.string4 DESC, tenk1.hundred) AS rank              +
    FROM tenk1                                                                                                                +
   GROUP BY tenk1.ten                                                                                                         +
   ORDER BY tenk1.ten;
(1 row)

select * from aggordview1 order by ten;
 ten | p50 | px  | rank 
-----+-----+-----+------
   0 | 490 |     |  101
   1 | 491 | 401 |  101
   2 | 492 |     |  101
   3 | 493 |     |  101
   4 | 494 |     |  101
   5 | 495 |     |   67
   6 | 496 |     |    1
   7 | 497 |     |    1
   8 | 498 |     |    1
   9 | 499 |     |    1
(10 rows)

drop view aggordview1;
-- variadic aggregates
select least_agg(q1,q2) from int8_tbl;
     least_agg     
-------------------
 -4567890123456789
(1 row)

select least_agg(variadic array[q1,q2]) from int8_tbl;
     least_agg     
-------------------
 -4567890123456789
(1 row)

select cleast_agg(q1,q2) from int8_tbl;
    cleast_agg     
-------------------
 -4567890123456789
(1 row)

select cleast_agg(4.5,f1) from int4_tbl;
 cleast_agg  
-------------
 -2147483647
(1 row)

select cleast_agg(variadic array[4.5,f1]) from int4_tbl;
 cleast_agg  
-------------
 -2147483647
(1 row)

select pg_typeof(cleast_agg(variadic array[4.5,f1])) from int4_tbl;
 pg_typeof 
-----------
 numeric
(1 row)

-- test aggregates with common transition functions share the same states
begin work;
create type avg_state as (total bigint, count bigint);
create or replace function avg_transfn(state avg_state, n int) returns avg_state as
$$
declare new_state avg_state;
begin
	raise notice 'avg_transfn called with %', n;
	if state is null then
		if n is not null then
			new_state.total := n;
			new_state.count := 1;
			return new_state;
		end if;
		return null;
	elsif n is not null then
		state.total := state.total + n;
		state.count := state.count + 1;
		return state;
	end if;

	return null;
end
$$ language plpgsql;
create function avg_finalfn(state avg_state) returns int4 as
$$
begin
	if state is null then
		return NULL;
	else
		return state.total / state.count;
	end if;
end
$$ language plpgsql;
create function sum_finalfn(state avg_state) returns int4 as
$$
begin
	if state is null then
		return NULL;
	else
		return state.total;
	end if;
end
$$ language plpgsql;
create aggregate my_avg(int4)
(
   stype = avg_state,
   sfunc = avg_transfn,
   finalfunc = avg_finalfn
);
create aggregate my_sum(int4)
(
   stype = avg_state,
   sfunc = avg_transfn,
   finalfunc = sum_finalfn
);
-- aggregate state should be shared as aggs are the same.
select my_avg(one),my_avg(one) from (values(1),(3)) t(one);
NOTICE:  avg_transfn called with 1
NOTICE:  avg_transfn called with 3
 my_avg | my_avg 
--------+--------
      2 |      2
(1 row)

-- aggregate state should be shared as transfn is the same for both aggs.
select my_avg(one),my_sum(one) from (values(1),(3)) t(one);
NOTICE:  avg_transfn called with 1
NOTICE:  avg_transfn called with 3
 my_avg | my_sum 
--------+--------
      2 |      4
(1 row)

-- same as previous one, but with DISTINCT, which requires sorting the input.
select my_avg(distinct one),my_sum(distinct one) from (values(1),(3),(1)) t(one);
NOTICE:  avg_transfn called with 1
NOTICE:  avg_transfn called with 3
 my_avg | my_sum 
--------+--------
      2 |      4
(1 row)

-- shouldn't share states due to the distinctness not matching.
select my_avg(distinct one),my_sum(one) from (values(1),(3)) t(one);
NOTICE:  avg_transfn called with 1
NOTICE:  avg_transfn called with 3
NOTICE:  avg_transfn called with 1
NOTICE:  avg_transfn called with 3
 my_avg | my_sum 
--------+--------
      2 |      4
(1 row)

-- shouldn't share states due to the filter clause not matching.
select my_avg(one) filter (where one > 1),my_sum(one) from (values(1),(3)) t(one);
NOTICE:  avg_transfn called with 1
NOTICE:  avg_transfn called with 3
NOTICE:  avg_transfn called with 3
 my_avg | my_sum 
--------+--------
      3 |      4
(1 row)

-- this should not share the state due to different input columns.
select my_avg(one),my_sum(two) from (values(1,2),(3,4)) t(one,two);
NOTICE:  avg_transfn called with 1
NOTICE:  avg_transfn called with 2
NOTICE:  avg_transfn called with 3
NOTICE:  avg_transfn called with 4
 my_avg | my_sum 
--------+--------
      2 |      6
(1 row)

-- exercise cases where OSAs share state
select
  percentile_cont(0.5) within group (order by a),
  percentile_disc(0.5) within group (order by a)
from (values(1::float8),(3),(5),(7)) t(a);
 percentile_cont | percentile_disc 
-----------------+-----------------
               4 |               3
(1 row)

select
  percentile_cont(0.25) within group (order by a),
  percentile_disc(0.5) within group (order by a)
from (values(1::float8),(3),(5),(7)) t(a);
 percentile_cont | percentile_disc 
-----------------+-----------------
             2.5 |               3
(1 row)

-- these can't share state currently
select
  rank(4) within group (order by a),
  dense_rank(4) within group (order by a)
from (values(1),(3),(5),(7)) t(a);
 rank | dense_rank 
------+------------
    3 |          3
(1 row)

-- test that aggs with the same sfunc and initcond share the same agg state
create aggregate my_sum_init(int4)
(
   stype = avg_state,
   sfunc = avg_transfn,
   finalfunc = sum_finalfn,
   initcond = '(10,0)'
);
create aggregate my_avg_init(int4)
(
   stype = avg_state,
   sfunc = avg_transfn,
   finalfunc = avg_finalfn,
   initcond = '(10,0)'
);
create aggregate my_avg_init2(int4)
(
   stype = avg_state,
   sfunc = avg_transfn,
   finalfunc = avg_finalfn,
   initcond = '(4,0)'
);
-- state should be shared if INITCONDs are matching
select my_sum_init(one),my_avg_init(one) from (values(1),(3)) t(one);
NOTICE:  avg_transfn called with 1
NOTICE:  avg_transfn called with 3
 my_sum_init | my_avg_init 
-------------+-------------
          14 |           7
(1 row)

-- Varying INITCONDs should cause the states not to be shared.
select my_sum_init(one),my_avg_init2(one) from (values(1),(3)) t(one);
NOTICE:  avg_transfn called with 1
NOTICE:  avg_transfn called with 1
NOTICE:  avg_transfn called with 3
NOTICE:  avg_transfn called with 3
 my_sum_init | my_avg_init2 
-------------+--------------
          14 |            4
(1 row)

rollback;
-- test aggregate state sharing to ensure it works if one aggregate has a
-- finalfn and the other one has none.
begin work;
create or replace function sum_transfn(state int4, n int4) returns int4 as
$$
declare new_state int4;
begin
	raise notice 'sum_transfn called with %', n;
	if state is null then
		if n is not null then
			new_state := n;
			return new_state;
		end if;
		return null;
	elsif n is not null then
		state := state + n;
		return state;
	end if;

	return null;
end
$$ language plpgsql;
create function halfsum_finalfn(state int4) returns int4 as
$$
begin
	if state is null then
		return NULL;
	else
		return state / 2;
	end if;
end
$$ language plpgsql;
create aggregate my_sum(int4)
(
   stype = int4,
   sfunc = sum_transfn
);
create aggregate my_half_sum(int4)
(
   stype = int4,
   sfunc = sum_transfn,
   finalfunc = halfsum_finalfn
);
-- Agg state should be shared even though my_sum has no finalfn
select my_sum(one),my_half_sum(one) from (values(1),(2),(3),(4)) t(one);
NOTICE:  sum_transfn called with 1
NOTICE:  sum_transfn called with 2
NOTICE:  sum_transfn called with 3
NOTICE:  sum_transfn called with 4
 my_sum | my_half_sum 
--------+-------------
     10 |           5
(1 row)

rollback;
-- test that the aggregate transition logic correctly handles
-- transition / combine functions returning NULL
-- First test the case of a normal transition function returning NULL
BEGIN;
CREATE FUNCTION balkifnull(int8, int4)
RETURNS int8
STRICT
LANGUAGE plpgsql AS $$
BEGIN
    IF $1 IS NULL THEN
       RAISE 'erroneously called with NULL argument';
    END IF;
    RETURN NULL;
END$$;
CREATE AGGREGATE balk(int4)
(
    SFUNC = balkifnull(int8, int4),
    STYPE = int8,
    PARALLEL = SAFE,
    INITCOND = '0'
);
SELECT balk(hundred) FROM tenk1;
 balk 
------
     
(1 row)

ROLLBACK;
-- Secondly test the case of a parallel aggregate combiner function
-- returning NULL. For that use normal transition function, but a
-- combiner function returning NULL.
BEGIN;
CREATE FUNCTION balkifnull(int8, int8)
RETURNS int8
PARALLEL SAFE
STRICT
LANGUAGE plpgsql AS $$
BEGIN
    IF $1 IS NULL THEN
       RAISE 'erroneously called with NULL argument';
    END IF;
    RETURN NULL;
END$$;
CREATE AGGREGATE balk(int4)
(
    SFUNC = int4_sum(int8, int4),
    STYPE = int8,
    COMBINEFUNC = balkifnull(int8, int8),
    PARALLEL = SAFE,
    INITCOND = '0'
);
-- force use of parallelism
ALTER TABLE tenk1 set (parallel_workers = 4);
SET LOCAL parallel_setup_cost=0;
SET LOCAL max_parallel_workers_per_gather=4;
EXPLAIN (COSTS OFF) SELECT balk(hundred) FROM tenk1;
                               QUERY PLAN                                
-------------------------------------------------------------------------
 Finalize Aggregate
   ->  Gather
         Workers Planned: 4
         ->  Partial Aggregate
               ->  Parallel Index Only Scan using tenk1_hundred on tenk1
(5 rows)

SELECT balk(hundred) FROM tenk1;
 balk 
------
     
(1 row)

ROLLBACK;
-- test coverage for aggregate combine/serial/deserial functions
BEGIN;
SET parallel_setup_cost = 0;
SET parallel_tuple_cost = 0;
SET min_parallel_table_scan_size = 0;
SET max_parallel_workers_per_gather = 4;
SET parallel_leader_participation = off;
SET enable_indexonlyscan = off;
-- variance(int4) covers numeric_poly_combine
-- sum(int8) covers int8_avg_combine
-- regr_count(float8, float8) covers int8inc_float8_float8 and aggregates with > 1 arg
EXPLAIN (COSTS OFF, VERBOSE)
SELECT variance(unique1::int4), sum(unique1::int8), regr_count(unique1::float8, unique1::float8)
FROM (SELECT * FROM tenk1
      UNION ALL SELECT * FROM tenk1
      UNION ALL SELECT * FROM tenk1
      UNION ALL SELECT * FROM tenk1) u;
                                                                                      QUERY PLAN                                                                                       
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Finalize Aggregate
   Output: variance(tenk1.unique1), sum((tenk1.unique1)::bigint), regr_count((tenk1.unique1)::double precision, (tenk1.unique1)::double precision)
   ->  Gather
         Output: (PARTIAL variance(tenk1.unique1)), (PARTIAL sum((tenk1.unique1)::bigint)), (PARTIAL regr_count((tenk1.unique1)::double precision, (tenk1.unique1)::double precision))
         Workers Planned: 4
         ->  Partial Aggregate
               Output: PARTIAL variance(tenk1.unique1), PARTIAL sum((tenk1.unique1)::bigint), PARTIAL regr_count((tenk1.unique1)::double precision, (tenk1.unique1)::double precision)
               ->  Parallel Append
                     ->  Parallel Seq Scan on public.tenk1
                           Output: tenk1.unique1
                     ->  Parallel Seq Scan on public.tenk1 tenk1_1
                           Output: tenk1_1.unique1
                     ->  Parallel Seq Scan on public.tenk1 tenk1_2
                           Output: tenk1_2.unique1
                     ->  Parallel Seq Scan on public.tenk1 tenk1_3
                           Output: tenk1_3.unique1
(16 rows)

SELECT variance(unique1::int4), sum(unique1::int8), regr_count(unique1::float8, unique1::float8)
FROM (SELECT * FROM tenk1
      UNION ALL SELECT * FROM tenk1
      UNION ALL SELECT * FROM tenk1
      UNION ALL SELECT * FROM tenk1) u;
       variance       |    sum    | regr_count 
----------------------+-----------+------------
 8333541.588539713493 | 199980000 |      40000
(1 row)

-- variance(int8) covers numeric_combine
-- avg(numeric) covers numeric_avg_combine
EXPLAIN (COSTS OFF, VERBOSE)
SELECT variance(unique1::int8), avg(unique1::numeric)
FROM (SELECT * FROM tenk1
      UNION ALL SELECT * FROM tenk1
      UNION ALL SELECT * FROM tenk1
      UNION ALL SELECT * FROM tenk1) u;
                                               QUERY PLAN                                               
--------------------------------------------------------------------------------------------------------
 Finalize Aggregate
   Output: variance((tenk1.unique1)::bigint), avg((tenk1.unique1)::numeric)
   ->  Gather
         Output: (PARTIAL variance((tenk1.unique1)::bigint)), (PARTIAL avg((tenk1.unique1)::numeric))
         Workers Planned: 4
         ->  Partial Aggregate
               Output: PARTIAL variance((tenk1.unique1)::bigint), PARTIAL avg((tenk1.unique1)::numeric)
               ->  Parallel Append
                     ->  Parallel Seq Scan on public.tenk1
                           Output: tenk1.unique1
                     ->  Parallel Seq Scan on public.tenk1 tenk1_1
                           Output: tenk1_1.unique1
                     ->  Parallel Seq Scan on public.tenk1 tenk1_2
                           Output: tenk1_2.unique1
                     ->  Parallel Seq Scan on public.tenk1 tenk1_3
                           Output: tenk1_3.unique1
(16 rows)

SELECT variance(unique1::int8), avg(unique1::numeric)
FROM (SELECT * FROM tenk1
      UNION ALL SELECT * FROM tenk1
      UNION ALL SELECT * FROM tenk1
      UNION ALL SELECT * FROM tenk1) u;
       variance       |          avg          
----------------------+-----------------------
 8333541.588539713493 | 4999.5000000000000000
(1 row)

ROLLBACK;
-- test coverage for dense_rank
SELECT dense_rank(x) WITHIN GROUP (ORDER BY x) FROM (VALUES (1),(1),(2),(2),(3),(3)) v(x) GROUP BY (x) ORDER BY 1;
 dense_rank 
------------
          1
          1
          1
(3 rows)

-- Ensure that the STRICT checks for aggregates does not take NULLness
-- of ORDER BY columns into account. See bug report around
-- 2a505161-2727-2473-7c46-591ed108ac52@email.cz
SELECT min(x ORDER BY y) FROM (VALUES(1, NULL)) AS d(x,y);
 min 
-----
   1
(1 row)

SELECT min(x ORDER BY y) FROM (VALUES(1, 2)) AS d(x,y);
 min 
-----
   1
(1 row)

-- check collation-sensitive matching between grouping expressions
select v||'a', case v||'a' when 'aa' then 1 else 0 end, count(*)
  from unnest(array['a','b']) u(v)
 group by v||'a' order by 1;
 ?column? | case | count 
----------+------+-------
 aa       |    1 |     1
 ba       |    0 |     1
(2 rows)

select v||'a', case when v||'a' = 'aa' then 1 else 0 end, count(*)
  from unnest(array['a','b']) u(v)
 group by v||'a' order by 1;
 ?column? | case | count 
----------+------+-------
 aa       |    1 |     1
 ba       |    0 |     1
(2 rows)

-- Make sure that generation of HashAggregate for uniqification purposes
-- does not lead to array overflow due to unexpected duplicate hash keys
-- see CAFeeJoKKu0u+A_A9R9316djW-YW3-+Gtgvy3ju655qRHR3jtdA@mail.gmail.com
set enable_memoize to off;
explain (costs off)
  select 1 from tenk1
   where (hundred, thousand) in (select twothousand, twothousand from onek);
                         QUERY PLAN                          
-------------------------------------------------------------
 Hash Join
   Hash Cond: (tenk1.hundred = onek.twothousand)
   ->  Seq Scan on tenk1
         Filter: (hundred = thousand)
   ->  Hash
         ->  HashAggregate
               Group Key: onek.twothousand, onek.twothousand
               ->  Seq Scan on onek
(8 rows)

reset enable_memoize;
--
-- Hash Aggregation Spill tests
--
set enable_sort=false;
set work_mem='64kB';
select unique1, count(*), sum(twothousand) from tenk1
group by unique1
having sum(fivethous) > 4975
order by sum(twothousand);
 unique1 | count | sum  
---------+-------+------
    4976 |     1 |  976
    4977 |     1 |  977
    4978 |     1 |  978
    4979 |     1 |  979
    4980 |     1 |  980
    4981 |     1 |  981
    4982 |     1 |  982
    4983 |     1 |  983
    4984 |     1 |  984
    4985 |     1 |  985
    4986 |     1 |  986
    4987 |     1 |  987
    4988 |     1 |  988
    4989 |     1 |  989
    4990 |     1 |  990
    4991 |     1 |  991
    4992 |     1 |  992
    4993 |     1 |  993
    4994 |     1 |  994
    4995 |     1 |  995
    4996 |     1 |  996
    4997 |     1 |  997
    4998 |     1 |  998
    4999 |     1 |  999
    9976 |     1 | 1976
    9977 |     1 | 1977
    9978 |     1 | 1978
    9979 |     1 | 1979
    9980 |     1 | 1980
    9981 |     1 | 1981
    9982 |     1 | 1982
    9983 |     1 | 1983
    9984 |     1 | 1984
    9985 |     1 | 1985
    9986 |     1 | 1986
    9987 |     1 | 1987
    9988 |     1 | 1988
    9989 |     1 | 1989
    9990 |     1 | 1990
    9991 |     1 | 1991
    9992 |     1 | 1992
    9993 |     1 | 1993
    9994 |     1 | 1994
    9995 |     1 | 1995
    9996 |     1 | 1996
    9997 |     1 | 1997
    9998 |     1 | 1998
    9999 |     1 | 1999
(48 rows)

set work_mem to default;
set enable_sort to default;
--
-- Compare results between plans using sorting and plans using hash
-- aggregation. Force spilling in both cases by setting work_mem low.
--
set work_mem='64kB';
create table agg_data_2k as
select g from generate_series(0, 1999) g;
analyze agg_data_2k;
create table agg_data_20k as
select g from generate_series(0, 19999) g;
analyze agg_data_20k;
-- Produce results with sorting.
set enable_hashagg = false;
set jit_above_cost = 0;
explain (costs off)
select g%10000 as c1, sum(g::numeric) as c2, count(*) as c3
  from agg_data_20k group by g%10000;
              QUERY PLAN              
--------------------------------------
 GroupAggregate
   Group Key: ((g % 10000))
   ->  Sort
         Sort Key: ((g % 10000))
         ->  Seq Scan on agg_data_20k
(5 rows)

create table agg_group_1 as
select g%10000 as c1, sum(g::numeric) as c2, count(*) as c3
  from agg_data_20k group by g%10000;
create table agg_group_2 as
select * from
  (values (100), (300), (500)) as r(a),
  lateral (
    select (g/2)::numeric as c1,
           array_agg(g::numeric) as c2,
	   count(*) as c3
    from agg_data_2k
    where g < r.a
    group by g/2) as s;
set jit_above_cost to default;
create table agg_group_3 as
select (g/2)::numeric as c1, sum(7::int4) as c2, count(*) as c3
  from agg_data_2k group by g/2;
create table agg_group_4 as
select (g/2)::numeric as c1, array_agg(g::numeric) as c2, count(*) as c3
  from agg_data_2k group by g/2;
-- Produce results with hash aggregation
set enable_hashagg = true;
set enable_sort = false;
set jit_above_cost = 0;
explain (costs off)
select g%10000 as c1, sum(g::numeric) as c2, count(*) as c3
  from agg_data_20k group by g%10000;
           QUERY PLAN           
--------------------------------
 HashAggregate
   Group Key: (g % 10000)
   ->  Seq Scan on agg_data_20k
(3 rows)

create table agg_hash_1 as
select g%10000 as c1, sum(g::numeric) as c2, count(*) as c3
  from agg_data_20k group by g%10000;
create table agg_hash_2 as
select * from
  (values (100), (300), (500)) as r(a),
  lateral (
    select (g/2)::numeric as c1,
           array_agg(g::numeric) as c2,
	   count(*) as c3
    from agg_data_2k
    where g < r.a
    group by g/2) as s;
set jit_above_cost to default;
create table agg_hash_3 as
select (g/2)::numeric as c1, sum(7::int4) as c2, count(*) as c3
  from agg_data_2k group by g/2;
create table agg_hash_4 as
select (g/2)::numeric as c1, array_agg(g::numeric) as c2, count(*) as c3
  from agg_data_2k group by g/2;
set enable_sort = true;
set work_mem to default;
-- Compare group aggregation results to hash aggregation results
(select * from agg_hash_1 except select * from agg_group_1)
  union all
(select * from agg_group_1 except select * from agg_hash_1);
 c1 | c2 | c3 
----+----+----
(0 rows)

(select * from agg_hash_2 except select * from agg_group_2)
  union all
(select * from agg_group_2 except select * from agg_hash_2);
 a | c1 | c2 | c3 
---+----+----+----
(0 rows)

(select * from agg_hash_3 except select * from agg_group_3)
  union all
(select * from agg_group_3 except select * from agg_hash_3);
 c1 | c2 | c3 
----+----+----
(0 rows)

(select * from agg_hash_4 except select * from agg_group_4)
  union all
(select * from agg_group_4 except select * from agg_hash_4);
 c1 | c2 | c3 
----+----+----
(0 rows)

drop table agg_group_1;
drop table agg_group_2;
drop table agg_group_3;
drop table agg_group_4;
drop table agg_hash_1;
drop table agg_hash_2;
drop table agg_hash_3;
drop table agg_hash_4;