Skip to content

Instantly share code, notes, and snippets.

@tatsushid
Created June 10, 2020 09:03
Show Gist options
  • Save tatsushid/7846796bc6260751b25e09cc01ce336a to your computer and use it in GitHub Desktop.
Save tatsushid/7846796bc6260751b25e09cc01ce336a to your computer and use it in GitHub Desktop.
-- testing with a table "foo" like following
--
-- start_ymd |end_ymd |val
-- ----------+----------+---
-- 2019-12-01|2020-02-29|bar
-- 2020-03-01|2020-05-31|qux
--
-- to convert it like
--
-- 201912|bar
-- 202001|bar
-- 202002|bar
-- 202003|qux
-- 202004|qux
-- 202005|qux
--
-- SQLite
select year.column1 * 100 + month.column1, foo.val
from (values(2019), (2020)) year,
(values(1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12)) month,
foo
where year.column1 * 100 + month.column1
between cast(substr(replace(foo.start_ymd, '-', ''), 1, 6) as decimal)
and cast(substr(replace(foo.end_ymd, '-', ''), 1, 6) as decimal)
order by 1;
-- PostgreSQL (not tested)
select year.n * 100 + month.n, foo.val
from (values(2019), (2020)) year(n),
(values(1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12)) month(n),
foo
where year.n * 100 + month.n
between cast(substring(replace(foo.start_ymd, '-', ''), 1, 6) as decimal)
and cast(substring(replace(foo.end_ymd, '-', ''), 1, 6) as decimal)
order by 1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment