I apologize in advance if the question is too basic. Window functions are fun and challenging at the same time!
I have two Postgres tables such as below called client and order.
id | name
------------
41 | james
29 | melinda
36 | henry
...
id | date | volume | client_id
------------------------------
328 | 2018-01-03 | 16 | 41
411 | 2018-01-29 | 39 | 29
129 | 2018-01-13 | 73 | 29
542 | 2018-01-22 | 62 | 36
301 | 2018-01-17 | 38 | 41
784 | 2018-01-08 | 84 | 29
299 | 2018-01-10 | 54 | 36
300 | 2018-01-10 | 18 | 36
178 | 2018-01-30 | 37 | 36
...
a) How can I write a query to find the largest difference in order volume for each client? For example, client_id = 36 should show (54 + 18) - 37 = -35. This is because orders placed on the same day by the same client should count as one order.
b) How can I find the difference in volume between the two most recent orders for each client? For example, client_id = 29 should show 39 - 73 = -34