Skip to content

Instantly share code, notes, and snippets.

@snoyes
Created December 2, 2022 14:30
Show Gist options
  • Save snoyes/935b991ca099453773e1bf0a19e39844 to your computer and use it in GitHub Desktop.
Save snoyes/935b991ca099453773e1bf0a19e39844 to your computer and use it in GitHub Desktop.
Advent of Code, day 1, in pure MySQL
CREATE TABLE day01 (elf int auto_increment primary key, calories JSON);
LOAD DATA LOCAL INFILE 'day01.txt' INTO TABLE day01
LINES TERMINATED BY '\n\n' (@cal)
SET calories = CONCAT('[', TRIM(TRAILING ',' FROM REPLACE(@cal, '\n', ',')), ']');
CREATE VIEW calories AS SELECT SUM(cal) AS cal
FROM day01
JOIN JSON_TABLE(calories, '$[*]' COLUMNS(cal int path '$')) jt GROUP BY elf ORDER BY cal DESC;
SELECT SUM(cal) AS part1 FROM (SELECT cal FROM calories LIMIT 1) dt;
SELECT SUM(cal) AS part2 FROM (SELECT cal FROM calories LIMIT 3) dt;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment