-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01.sql
More file actions
83 lines (69 loc) · 1.76 KB
/
Copy path01.sql
File metadata and controls
83 lines (69 loc) · 1.76 KB
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
81
82
83
DROP TABLE IF EXISTS calibration;
CREATE TABLE IF NOT EXISTS calibration (
calibration TEXT,
id SERIAL
);
COPY calibration(calibration)
FROM 'PATH_TO_01.txt'
;
-- part 1:
WITH
digits as (
SELECT
regexp_replace(calibration, '[[:alpha:]]', '', 'g') as trimmed
from calibration
),
numbers as (
select
cast (
-- first digit
left(trimmed, 1)
||
-- last digit
right(trimmed,1)
as integer
)as number
from digits),
total as (
select
sum(number)
from numbers
)
select * from total;
-- part 2:
WITH
trimmed as (
select
array(SELECT
regexp_matches(
calibration,
'[1-9]|one|two|three|four|five|six|seven|eight|nine',
'g')
) as trimmed
from calibration
),
numbers as (
select
trimmed[1][1] as first_digit,
trimmed[array_upper(trimmed,1)][1] as second_digit
from trimmed
),
dictionary as (
select array['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] as words
),
digits as (
select
COALESCE(array_position(dictionary.words, first_digit),
CAST(first_digit as integer)
) as first_digit,
COALESCE(array_position(dictionary.words, second_digit),
CAST(second_digit as integer)
) as second_digit
from numbers, dictionary
),
total as (
select
sum(first_digit*10+second_digit)
from digits
)
select * from total;