从状态更改历史记录中获取每一天的发布状态

时间:2016-09-16 15:27:54

标签: sql postgresql

有一个表<pluginManagement>,它是帖子状态更改的历史记录

post_status_changes

我想得到的是从DayA到发布状态BB的每一天的列表,以便结束日期。

 post_id |         created_at  | status
---------+---------------------+---------
       3 | 2016-09-02 04:00:00 | 1      
       3 | 2016-09-04 19:59:21 | 2     
       6 | 2016-09-03 15:00:00 | 5      
       6 | 2016-09-03 19:52:46 | 1      
       6 | 2016-09-04 20:53:22 | 2  
DayA = 2016-09-01
DayB = 2016-09-05

任何解决方案?

3 个答案:

答案 0 :(得分:0)

解决方案在此处找到:PHP: Return all dates between two dates in an array

$period = new DatePeriod(
     new DateTime('2010-10-01'),
     new DateInterval('P1D'),
     new DateTime('2010-10-05')
);

foreach ($period as $each){
   //.. QUERY here, where "CREAtED_AT" = $each
}

答案 1 :(得分:0)

对于每个post_id,您需要的行数与开始日期和结束日期之间的天数相同。这可以通过将日期列表与post_ids交叉连接来完成,然后将该结果加回到表中以获取每天的状态:

select x.post_id, t.created, p.status
from generate_series(date '2016-09-01', date '2016-09-05', interval '1' day) as t(created)
  cross join (
     select distinct post_id 
     from post_status_changes
  ) x
  left join post_status_changes p on p.created_at::date = t.created
order by 1,2;

正在运行示例:http://rextester.com/CSX38222

答案 2 :(得分:0)

with a as 
    (select convert(varchar(10), created_at, 102) [date], [status], 
    post_id, rank() over (partition by convert(varchar(10), created_at), 
    post_id order by created_at desc) as r 
    from post_status_changes)
select post_id, [date], [status] from a where r = 
    (select top 1 r from a as a2 where a.[date] = 
    a2.[date] and a.[post_id] = a2.[post_id])
    and @DayA <= [date] and @DayB >= [date] order by post_id, [date];