简体   繁体   中英

Postgres Calculate Difference Using Window Functions

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

Well here is a T-SQL.
For this formula as you said ---> Max(total volume each day) - Min(total volume each day)
May help you.

SELECT (X.Max(SumV)-X.Min(SumV))
From (
     SELECT Client_Id,Date,SUM(Volume) AS SumV
     FROM Orders
     GROUP BY Client_id,Date
     ) X

Group by X.Client_Id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM