[英]PostgreSQL group by with interval but without window functions
This is follow-up of my previous question: 这是我之前的问题的后续内容:
PostgreSQL group by with interval PostgreSQL按间隔分组
There was a very good answer but unfortunately it is not working with PostgreSQL 8.0 - some clients still use this old version. 有一个很好的答案,但是不幸的是它不能在PostgreSQL 8.0上工作-一些客户端仍然使用这个旧版本。
So I need to find another solution without using window functions 所以我需要在不使用窗口功能的情况下找到另一种解决方案
Here is what I have as a table: 这是我的桌子:
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
I need to sum "quantity" grouped by "price1" and "price2" but only when they change 我需要对按“ price1”和“ price2”分组的“数量”求和,但仅当它们改变时
So the end result should look like this: 因此,最终结果应如下所示:
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
It is not efficient, but you can implement the same logic with subqueries: 它效率不高,但是可以通过子查询实现相同的逻辑:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.