Example data:
id | docn | item | suma
---------------------
1 33 x | 10
1 33 y | 20
2 37 a | 10
2 37 b | 20
2 37 c | 30
To group results I can write:
SELECT sum( suma ),
(ocd.o).*
FROM order_cost_details() ocd
where (ocd.o).id IN ( 6154, 10805 )
GROUP BY ocd.o
But in a place with a group I want to select last_value
for each group. Next does not work:
SELECT sum( suma ),
(ocd.o).*,
last_value( ocd.c ) OVER (PARTITION BY ocd.o )
FROM order_cost_details() ocd
where (ocd.o).id IN ( 6154, 10805 )
GROUP BY ocd.o
SQL Error [42803]: ERROR: column "ocd.c" must appear in the GROUP BY clause or be used in an aggregate function
I rewrite my query like next:
SELECT DISTINCT sum( suma ) OVER ( PARTITION BY ocd.o ),
(ocd.o).*,
last_value( ocd.c ) OVER (PARTITION BY ocd.o )
FROM order_cost_details() ocd
where (ocd.o).id IN ( 6154, 10805 )
Results seems expected:
with correct
last_value
:
But I am not sure is this correct to use DISTINCT
instead of GROUP BY
here?