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
并且表格以不同的日期继续, 我想找到每个日期和出现的差异(a-b)..即
diff total date
a-b 70 1/2/2015
a-b 7 2/2/2015....
我如何在postgresql中执行此操作
答案 0 :(得分:1)
使用nth_value()
窗口功能:
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)