简体   繁体   English

Postgres使用窗口函数计算差异

[英]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. 我有两个Postgres表,如下面称为客户端和订单。

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? a)如何编写查询以查找每个客户端订单量的最大差异? For example, client_id = 36 should show (54 + 18) - 37 = -35 . 例如, client_id = 36应显示(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? b)如何找到每个客户的两个最近订单之间的数量差异? For example, client_id = 29 should show 39 - 73 = -34 例如, client_id = 29应显示39 - 73 = -34

Well here is a T-SQL. 那么这是一个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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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