-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyears2.sql
80 lines (76 loc) · 1.36 KB
/
years2.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
with "table6" as (select
o."uniq",
y.*
from
ng."original" o
-- "original" o
join (
select
row_number() over() seq,
"original" "start_date1",
lead("original") over() "end_date1"
from (
select
"original"
from
ng."original"
-- "original"
group by
"original"
order by
"original"
) g
) y on y.start_date1 = o."original"
order by
"uniq",
"original"
)
select
"uniq",
"start_date",
"end_date"
from
(
select
"uniq", "dmin", "dmax",
min(case when "first" = "seq" then "start_date1" else null end) "start_date",
max(case when "last" = "seq" then "end_date1" else null end) "end_date"
from (
select
m.*,
min("seq") over(partition by "uniq", "dmin", "dmax") "first",
max("seq") over(partition by "uniq", "dmin", "dmax" ) "last"
from
(
select
d.*,
min("diff") over (partition by "uniq" order by "seq") "dmin",
max("diff") over (partition by "uniq" order by "seq") "dmax"
from
(
select
t.*,
coalesce("seq" - lag("seq") over(partition by "uniq" order by "seq"), 1) "diff"
from
"table6" t
) d
order by
"uniq",
"seq"
) m
order by
"uniq",
"seq"
) g
group by
"uniq", "dmin", "dmax"
) f
group by
"uniq",
"start_date",
"end_date"
order by
"uniq",
"start_date"
--UPDATE original SET end_date = 1640
--WHERE end_date IS NULL;