【问题标题】:Comparing record to previous record in postgresql将记录与postgresql中的先前记录进行比较
【发布时间】:2012-02-24 15:04:24
【问题描述】:

我在 PostgreSQL 数据库中有一个这样的表:

 Client | Rate | StartDate|EndDate     
 A      | 1000 | 2005-1-1 |2005-12-31
 A      | 2000 | 2006-1-1 |2006-12-31
 A      | 3000 | 2007-1-1 |2007-12-31  
 B      | 5000 | 2006-1-1 |2006-12-31  
 B      | 8000 | 2008-1-1 |2008-12-31  
 C      | 2000 | 2006-1-1 |2006-12-31  

如何得到这个结果?

 Client | Rate | StartDate|EndDate    |Pre Rate | Pre StartDate |Pre EndDate    
 A      | 1000 | 2005-1-1 |2005-12-31 |         |               |             
 A      | 2000 | 2006-1-1 |2006-12-31 | 1000    | 2005-1-1      |2005-12-31            
 A      | 3000 | 2007-1-1 |2007-12-31 | 2000    | 2006-1-1      |2006-12-31  
 B      | 5000 | 2006-1-1 |2006-12-31 |         |               |              
 B      | 8000 | 2008-1-1 |2008-12-31 | 5000    | 2006-1-1      |2006-12-31   
 C      | 2000 | 2006-1-1 |2006-12-31 

非常感谢!!!

【问题讨论】:

    标签: postgresql comparison max next seconds


    【解决方案1】:
    SELECT client, 
           rate,
           startdate, 
           enddate, 
           lag(rate) over client_window as pre_rate,
           lag(startdate) over client_window as pre_startdate,
           lag(enddate) over client_window as pre_enddate
    FROM the_table
    WINDOW client_window as (partition by client order by startdate)
    ORDER BY client, stardate;
    

    这假设 enddate 总是大于同一行的 startdate,并且没有 enddate 大于以下 startdate

    【讨论】:

    • WINDOW client_window 别名很好,注意到一个
    • 我在不知情的情况下解决了类似的问题。只能说不好看。谢谢分配。
    猜你喜欢
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多