我正在研究Postgres并遇到这个我无法解决的有趣问题。
假设一家公司在几天内发货一次。这是发货表,用于记录发货的容器数量:
New York 2014-01-01 10
New York 2014-01-02 2
New York 2014-01-05 30
New York 2014-01-07 4
Toronto 2014-01-01 5
Toronto 2014-01-03 55
Toronto 2014-01-05 50
London 2014-01-01 60
London 2014-01-07 63
London 2014-01-12 64
我想要这份报告:
New York 2014-01-01 10 NULL NULL NULL
New York 2014-01-02 2 2014-01-01 10 -8
New York 2014-01-05 30 2014-01-02 2 28
New York 2014-01-07 4 2014-01-05 30 -26
Toronto 2014-01-01 5 NULL NULL NULL
Toronto 2014-01-03 55 2014-01-01 5 50
Toronto 2014-01-05 50 2014-01-03 55 -5
London 2014-01-01 60 NULL NULL NULL
London 2014-01-07 63 2014-01-01 60 3
London 2014-01-12 64 2014-01-07 63 1
我用这个:
Select a.*, b.*, (a.containers – b.containers) delta
From shipping a
Join shipping b
ON
b.date=(select date from shipping where date<a.date order by date desc limit 1)
当表很小时,这种方法有效。如果表增长到100,000条记录,则此查询速度很慢。我想知道你的家伙是否有更高效的方式。
谢谢, 斯蒂芬
答案 0 :(得分:1)
只需使用lag()
功能!
Select s.Branch, s.Date, s.containers,
lag(s.Date) over (partition by branch order by date) as prev_Date,
lag(s.containers) over (partition by branch order by date) as prev_Containers
from shipping s;