postgresql中日期条件的差异

difference on date condition in postgresql

name  total     date 
a     100     1/2/2015 
b     30      1/2/2015 
c     40      1/2/2015 
d     45      1/2/2015 
a     20      2/2/2015
b     13      2/2/2015 
a     30      3/2/2015
b     23      3/2/2015
c     20      3/2/2015

和 table 继续不同的日期, 我想找出每个日期和发生的差异 (a-b) .. 即

diff  total  date 
a-b    70    1/2/2015
a-b    7     2/2/2015.... 

如何在 postgresql 中实现

为此使用 nth_value() window 函数:

WITH t(name,total,date) AS ( VALUES
  ('a',100,'2016-01-01'::DATE),
  ('b',30,'2016-01-01'::DATE),
  ('c',40,'2016-01-01'::DATE),
  ('d',45,'2016-01-01'::DATE),
  ('a',20,'2016-01-02'::DATE),
  ('b',13,'2016-01-02'::DATE)
)
SELECT
  DISTINCT ON (date)
  'a-b' AS diff,
  (nth_value(total,1) OVER (PARTITION BY date) -
  nth_value(total,2) OVER (PARTITION BY date)) total_diff,
  date
FROM t
WHERE name IN ('a','b');

结果:

 diff | total_diff |    date    
------+------------+------------
 a-b  |         70 | 2016-01-01
 a-b  |          7 | 2016-01-02
(2 rows)