I'm wondering how to mix selecting columns, aggregated values as well as 'selects-from-partitions'. Please let me know if this is a duplicate question!
An example of what I mean:
Given example transaction log:
ID Food Date Cost
1 Apple 5/1/14 10
1 Apple 5/4/14 8
1 Apple 5/6/14 15
1 Pear 5/2/14 25
2 Apple 5/3/14 15
The goal is to select for each unique ID/Food combination, the cost of the first purchase (by date), last purchase as well as average cost.
The output would look like:
ID Food First_Cost Last_Cost Avg_Cost
1 Apple 10 15 11
1 Pear 25 25 25
2 Apple 15 15 15
I've looked into OVER - PARTITION (Select first row in each GROUP BY group?) as well as grouping alongside aggregate functions (https://dba.stackexchange.com/questions/41494/select-first-row-grouping-add-aggregate-function) but neither seemed to answer this specific question.
This is a code example of what I'm trying to accomplish:
select id
,food
,firstrow(cost) OVER(PARTITION BY id, food ORDER BY date asc as first_cost
,avg(cost) from table
group by id, food;
Using the ROWNUMBER() OVER(PARTITION...)
and then filtering with the where-clause doesn't seem to work either since the aggregate functions would be off.
One solution could always be to create a table with the first, one with last, one with average and join the three together, but I'm looking for something cleaner.
EDIT: From jpw's comment, Aster does have the first_value() window function. However, the issue with it is that the columns that I order or partition by must be included in the groupby clause. His suggestion and one solution could be to change all aggregate functions into window functions and eliminate the groupby altogether.
Would still like to see a cleaner solution or confirmation that this isn't possible!