Postgresql介于最小值之间

时间:2017-03-09 08:32:35

标签: sql postgresql

使用Postgresql 9.6表结构,如:

who | when

每天都有多条记录,其中 。 Ipotetically每个记录是 out 操作,因此需要为每个人获取总时间。

即。

who | when
  A | 2017-03-01 08:00 
  A | 2017-03-01 12:00
  A | 2017-03-01 13:00
  A | 2017-03-01 15:00

如何才能获得 6 小时的总数?

我认为max(when) - min(when)获取周期但需要减去计算中间最小值和最大值的中间数据。

因此需要将12:00作为早晨'和13:00作为'下午'但是当我把最小最大值放在抱怨的地方时

  

'在'

中没有可能的聚合函数
select who, 
      to_char(date_trunc('day', when), 'YYYY-MM-DD')  "thisday", 
       count(who) as 'signIn'
       min(when) as 'morningout'          
       max(when) as 'afternoonin' 


from the_table 
where when between max(when) and min(when)

group by who, "thisday"
order by who;

1 个答案:

答案 0 :(得分:2)

您可以使用window functions执行此操作:

[\\s;\\(\\),]+(?!('[^']+'))

如果您每天需要 ,只需使用select who, sum("when" - lag) from (select row_number() over w, who, "when", lag("when") over w from t window w as (partition by who order by "when")) d where row_number % 2 = 0 group by who 子句中的date_trunc('day', "when")即可。您还可以将group by放在窗口定义中的date_trunc('day', "when")子句中,以避免跨越几天的配对:

partition by

但是,这些解决方案要求行必须位于 + out 对中。要获得更可靠的解决方案,您需要select who, date_trunc('day', "when"), sum("when" - lag) from (select row_number() over w, who, "when", lag("when") over w from t window w as (partition by who, date_trunc('day', "when") order by "when")) d where row_number % 2 = 0 group by who, date_trunc('day', "when") 列。

http://rextester.com/UJWWH59178