【问题标题】:PostgreSQL aggregate and avg on colum value biasPostgreSQL 聚合和平均列值偏差
【发布时间】:2014-09-07 10:19:01
【问题描述】:

我想知道是否可以在 psql 中获取一组符合此条件的行

表 1/0 23 没有时区的时间戳

让我们想象一组数据

1  12 2014-07-14 09:01:00
1  13 2014-07-14 09:02:00
1  14 2014-07-14 09:03:00
1  15 2014-07-14 09:04:00
0  16 2014-07-14 09:05:00
0  17 2014-07-14 09:06:00
0  18 2014-07-14 09:07:00
1  17 2014-07-14 09:08:00
1  16 2014-07-14 09:09:00

我想按状态检索数据组,但保持日期顺序和状态变化。

即:

1 <avg temp> <avg date> (calculated over the first 4 rows)
0 <avg temp> <avg date> (calculated for the 3 rows with 0)
1 <avg temp> <avg date> (calculated for the last 2 rows)

基本上 1/0 表示加热器开/关,我想 计算平均温度,但按此加热器的状态分组

附言:

显然是一个简单的 select avg(temp),status from log group by status 不会成功,它只会返回 1/0 值,而不是范围和开/关之间的变化

另一个很好处理的情况是保持每个状态更改的第一条记录不变。

即:

1 <temp> <date> (calculated over the first)
1 <avg temp> <avg date> (calculated over the first 3 rows)
0 <temp> <date> (for the row 4)
0 <avg temp> <avg date> (from 5 to 6)
1 <temp> <date> (row 7)

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    是的,这是可能的。这是一种使用窗口函数的方法。它会生成一个标志来查看一行的状态是否与前一行不同,然后进行累积和:

    select t.*, sum(statuschange) over (order by date) as grp
    from (select t.*,
                 (case when lag(status) over (order by date) <> status then 1
                       else 0
                  end) as statuschange
          from table t
         ) t;
    

    剩下的只是在这个字段上分组:

    select status, avg(temp), min(date), max(date)
    from (select t.*, sum(statuschange) over (order by date) as grp
          from (select t.*,
                       (case when lag(status) over (order by date) <> status then 1
                             else 0
                        end) as statuschange
                from table t
               ) t
         ) t
    group by grp, status;
    

    我不确定在 Postgres 中求平均日期的最佳方法,因此这包括最小值和最大值。您的问题似乎更多是关于定义组,而不是获取日期/时间列的平均值。

    【讨论】:

    • 有趣,这正是我一直在寻找的,现在让它更复杂一点,是否可以做同样的事情,让每个“变化”的第一个样本保持不变?有关编辑问题的更多信息
    • @user3804873 。 . .在回答完问题后更改问题通常是不礼貌的。我不确定您所说的“保持原样”样品是什么意思。如果您不想包含它,可以通过在中间子查询中包含 where statuschange = 0 来实现。
    • 对不起,我还是 stackoverflow 的新手!
    猜你喜欢
    • 1970-01-01
    • 2015-03-05
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    相关资源
    最近更新 更多