这是我之前问题的后续:
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/