sql - PostgreSQL group by with interval 但没有窗口函数

标签 sql postgresql gaps-and-islands

这是我之前问题的后续:

PostgreSQL group by with interval

有一个很好的答案,但不幸的是它不适用于 PostgreSQL 8.0 - 一些客户仍在使用这个旧版本。

所以我需要寻找另一种不使用窗口函数的解决方案

这是我的表格:

   id quantity  price1  price2 date
    1  100       1       0      2018-01-01 10:00:00
    2  200       1       0      2018-01-02 10:00:00
    3  50        5       0      2018-01-02 11:00:00
    4  100       1       1      2018-01-03 10:00:00
    5  100       1       1      2018-01-03 11:00:00
    6  300       1       0      2018-01-03 12:00:00

我需要对按“price1”和“price2”分组的“数量”求和,但只有当它们发生变化时才需要这样做

所以最终结果应该是这样的:

quantity price1 price2 dateStart            dateEnd
300      1      0      2018-01-01 10:00:00  2018-01-02 10:00:00 
50       5      0      2018-01-02 11:00:00  2018-01-02 11:00:00
200      1      1      2018-01-03 10:00:00  2018-01-03 11:00:00
300      1      0      2018-01-03 12:00:00  2018-01-03 12:00:00

最佳答案

效率不高,但您可以使用子查询实现相同的逻辑:

select sum(quantity), price1, price2,
       min(date) as dateStart, max(date) as dateend 
from (select d.*,
             (select count(*)
              from data d2
              where d2.date <= d.date
             ) as seqnum,
             (select count(*)
              from data d2
              where d2.price1 = d.price1 and d2.price2 = d.price2 and d2.date <= d.date
             ) as seqnum_pp
      from data d
     ) t
group by price1, price2, (seqnum - seqnum_pp)
order by dateStart

关于sql - PostgreSQL group by with interval 但没有窗口函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48904228/

相关文章:

ruby-on-rails - 设置设备管理员角色

database - 将列复制到 PostgreSQL 中的同一个表

sql - 通过另一个表中的值限制表中的行数

postgresql - 在 docker-compose up 后加载 Postgres 转储

捕获具有不同 id 的相似行的 SQL 语句

MySQL:即使没有记录也选择一个范围内的所有日期

sql - 按值组的连续日期范围对行进行分组

mysql - 如何在 mysql 表中查找缺失的行(日期)?

php - 尝试从表中删除数据,但在用户单击删除之前不知道 ID。数据库

mysql - sql中如何从给定的月份和年份中获取该月的第一天和最后一天