简体   繁体   中英

PostgreSQL calculate difference between multi rows

I tried to calculate difference between rows in a field using a query:

Illustrations: input:year,month,name, size output:increase

 year | month  | name    | Size  | increase
------+--------+------- -+-------+-----------
 2020 | 01     |  john   |10     | 0
 2020 | 01     |  peter  |12     | 0
 2020 | 01     |  kim    |16     | 0

 2020 | 02     |  john   |15     | 5  <- 15 - 10
 2020 | 02     |  peter  |16     | 4  <- 16 - 12
 2020 | 02     |  kim    |17     | 1  <- 17 - 16

 2020 | 03     |  john   |18     | 3  <- 18 - 16
 2020 | 03     |  peter  |19     | 3  <- 19 - 16
 2020 | 03     |  kim    |77     | 60 <- 77 - 17


         -------
 2020 | 12     |  john   |25     | 17
 2020 | 12     |  peter  |70     | 33
 2020 | 12     |  kim    |90     |42

Increase column as output by difference between adjacent "name" rows in size.

Use LAG()

select year, 
  month, 
  name, 
  size, 
  size - lag(size) over (partition by name order by year, month) as increase
from MyTable

If you want 0 s for the first set of rows, then use the 3-argument form of lag() :

select year, month,  name, size, 
       (size - lag(size, 1, size)) over (partition by name order by year, month) as increase
from MyTable;

Personally, I prefer NULL so I prefer JohnHC's answer. However, the question is explicitly asking for 0 values there.

Thanks JohnHC and Gorden for helping.

It works when I run the query on psql commandline. But when I put it into a php script:

$result = pg_query($conn,"select year, month, name, (size - lag(size, 1, size)) over (partition by name order by year, month). as increase from testdb ");

I get error message:

PHP Warning: pg_query(): Query failed: ERROR: syntax error at or near '- lag(size)......'

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