sql—获取配置单元中每个id的连续t日期范围

pgpifvop  于 2021-06-24  发布在  Hive
关注(0)|答案(1)|浏览(561)

我有一个数据表,比如:

col1  col2
1      2020-01-15
1      2020-01-16
1      2020-01-17
1      2020-01-18
1      2020-01-20
2      2020-01-09
2      2020-01-10
2      2020-01-15

我想要这样的输出

col1    min         max
1      2020-01-15  2020-01-18
1      2020-01-20  2020-01-20
2      2020-01-09  2020-01-10
2      2020-01-15  2020-01-15

如您所见,对于每个id,我需要每个连续的ate块的日期范围,如果只有一个日期,那么minmax将是相同的

qhhrdooz

qhhrdooz1#

请尝试以下操作,下面是sql server中的演示。

select
  col1,
  min(col2) as mn,
  max(col2) as mx
from
(
  select
    col1,
    col2,
    date_sub(col2, -row_number() over (partition by col1 order by col2)) as rnk
  from myTable
) val
group by
  col1,
  rnk
order by
  col1

输出:


* -------------------------------*

| col1      mn          mx      |

* -------------------------------*

| 1    2020-01-15    2020-01-18 |
| 1    2020-01-20    2020-01-20 |
| 2    2020-01-09    2020-01-10 |
| 2    2020-01-15    2020-01-15 |

* -------------------------------*

相关问题