gpt4 book ai didi

sql - GROUP BY 由空格分隔的连续日期

转载 作者:行者123 更新时间:2023-11-29 11:16:07 24 4
gpt4 key购买 nike

假设您(在 Postgres 9.1 中)有一个这样的表:

date | value 

其中有一些空白(我的意思是:并非 min(date) 和 max(date) 之间的每个可能日期都有它的行)。

我的问题是如何聚合这些数据,以便每个一致的组(没有间隙)被单独处理,如下所示:

min_date | max_date | [some aggregate of "value" column] 

有什么办法吗?我相信使用窗口函数是可能的,但在尝试使用 lag()lead() 一段时间后,我有点卡住了。

例如如果数据是这样的:

 date          | value  
---------------+-------
2011-10-31 | 2
2011-11-01 | 8
2011-11-02 | 10
2012-09-13 | 1
2012-09-14 | 4
2012-09-15 | 5
2012-09-16 | 20
2012-10-30 | 10

输出(对于 sum 作为聚合)将是:

   min     |    max     |  sum  
-----------+------------+-------
2011-10-31 | 2011-11-02 | 20
2012-09-13 | 2012-09-16 | 30
2012-10-30 | 2012-10-30 | 10

最佳答案

create table t ("date" date, "value" int);
insert into t ("date", "value") values
('2011-10-31', 2),
('2011-11-01', 8),
('2011-11-02', 10),
('2012-09-13', 1),
('2012-09-14', 4),
('2012-09-15', 5),
('2012-09-16', 20),
('2012-10-30', 10);

更简单、更便宜的版本:

select min("date"), max("date"), sum(value)
from (
select
"date", value,
"date" - (dense_rank() over(order by "date"))::int g
from t
) s
group by s.g
order by 1

我的第一次尝试更加复杂和昂贵:

create temporary sequence s;
select min("date"), max("date"), sum(value)
from (
select
"date", value, d,
case
when lag("date", 1, null) over(order by s.d) is null and "date" is not null
then nextval('s')
when lag("date", 1, null) over(order by s.d) is not null and "date" is not null
then lastval()
else 0
end g
from
t
right join
generate_series(
(select min("date") from t)::date,
(select max("date") from t)::date + 1,
'1 day'
) s(d) on s.d::date = t."date"
) q
where g != 0
group by g
order by 1
;
drop sequence s;

输出:

    min     |    max     | sum 
------------+------------+-----
2011-10-31 | 2011-11-02 | 20
2012-09-13 | 2012-09-16 | 30
2012-10-30 | 2012-10-30 | 10
(3 rows)

关于sql - GROUP BY 由空格分隔的连续日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13009893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com