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
...
Then I wrote a query with the following logic:
i) Find the difference in volume between every order and its previous order, grouped by each client and order by date. This column will be null for first orders.
ii) Show clients and the maximum difference in volume for each of them.
with cte AS
(SELECT t.name,
t.date,
t.volume,
t.volume - lag(t.volume) over (
ORDER BY t.name, t.date) AS change
FROM
(SELECT c.name,
o.date,
sum(o.volume) volume
FROM orders o
JOIN client c using (client_id)
GROUP BY c.name,
o.date
ORDER BY c.name,
o.date) t)
SELECT cte.name,
max(abs(change))
FROM cte
GROUP BY name
Below is the resulting table.
name | max
------------
james | 22
melinda | 34
henry | 25
I am looking to get advice on three things.
a) Is it possible to show the difference with sign? For client ids 29 and 36, the values should be -34 and -25, respectively.
b) Is it possible to show the date as well? I tried to select the date column on CTE, but did not succeed.
c) Would anyone have any general advice on how I can improve the query to make it more performant or readable?