--
-- MULTI_AVERAGE_EXPRESSION_ORDER
--
-- This test checks that the group-by columns don't need to be above an average
-- expression, and can be anywhere in the projection order. This is in response
-- to a bug we had due to the average expression introducing new columns.
SELECT
	sum(l_quantity) as sum_qty,
	sum(l_extendedprice) as sum_base_price,
	sum(l_extendedprice * (1 - l_discount)) as sum_disc_price,
	sum(l_extendedprice * (1 - l_discount) * (1 + l_tax)) as sum_charge,
	avg(l_quantity) as avg_qty,
	avg(l_extendedprice) as avg_price,
	avg(l_discount) as avg_disc,
	count(*) as count_order,
	l_returnflag,
	l_linestatus
FROM
	lineitem
WHERE
	l_shipdate <= date '1998-12-01' - interval '90 days'
GROUP BY
	l_returnflag,
	l_linestatus
ORDER BY
	l_returnflag,
	l_linestatus;
  sum_qty  | sum_base_price | sum_disc_price |    sum_charge    |       avg_qty       |     avg_price      |        avg_disc        | count_order | l_returnflag | l_linestatus
---------------------------------------------------------------------
  75465.00 |   113619873.63 | 107841287.0728 | 112171153.245923 | 25.6334918478260870 | 38593.707075407609 | 0.05055027173913043478 |        2944 | A            | F
   2022.00 |     3102551.45 |   2952540.7118 |   3072642.770652 | 26.6052631578947368 | 40823.045394736842 | 0.05263157894736842105 |          76 | N            | F
 149778.00 |   224706948.16 | 213634857.6854 | 222134071.929801 | 25.4594594594594595 | 38195.979629440762 | 0.04939486656467788543 |        5883 | N            | O
  73156.00 |   108937979.73 | 103516623.6698 | 107743533.784328 | 25.2175112030334367 | 37551.871675284385 | 0.04983798690106859704 |        2901 | R            | F
(4 rows)

-- These tests check that distributed averages only consider non-null input
-- values. This is in response to a bug we had due to the distributed average
-- using sum(expression)/count(*) to calculate avg(expression). We now use the
-- correct form sum(expression)/count(expression) for average calculations.
-- Run avg() on an expression that contains some null values
SELECT
    avg(case
            when l_quantity > 20
            then l_quantity
        end)
FROM
    lineitem;
         avg
---------------------------------------------------------------------
 35.3570440077497924
(1 row)

-- Run avg() on an expression that contains only null values
SELECT
    avg(case
            when l_quantity > 5000
            then l_quantity
        end)
FROM
    lineitem;
 avg
---------------------------------------------------------------------

(1 row)

