Skip to content

Instantly share code, notes, and snippets.

@rkh
Created July 21, 2010 13:07
Show Gist options
  • Save rkh/484454 to your computer and use it in GitHub Desktop.
Save rkh/484454 to your computer and use it in GitHub Desktop.
select
yearweek(field, 1)
from
table;
select
EXTRACT(isoyear from field)*100 + EXTRACT(week from field - (EXTRACT(dow FROM field)::int+6)%7)
from
table;
select
case
when strftime('%W', strftime('%Y-01-04', field)) = '00' then
-- 01/01 is in week 1 of the current year => %W == week - 1
case
when strftime('%W', field) = '52' and strftime('%W', (strftime('%Y', field) + 1) || '-01-04') = '00' then
-- we are at the end of the year, and it's the first week of the next year
(strftime('%Y', field) + 1) || '01'
when strftime('%W', field) < '08' then
-- we are in week 1 to 9
strftime('%Y0', field) || (strftime('%W', field) + 1)
else
-- we are in week 10 or later
strftime('%Y', field) || (strftime('%W', field) + 1)
end
else
-- 01/01 is in week 53 of the last year
case
when strftime('%W', field) = '52' and strftime('%W', (strftime('%Y', field) + 1) || '-01-01') = '00' then
-- we are at the end of the year, and it's the first week of the next year
(strftime('%Y', field) + 1) || '01'
when strftime('%W', field) = '00' then
-- we are in the week belonging to last year
(strftime('%Y', field) - 1) || '53'
else
-- everything is fine
strftime('%Y%W', field)
end
end
from
table;
@timfel
Copy link

timfel commented Jul 21, 2010

This is why everyone knows SQlite is so AWESOME!

@bastih
Copy link

bastih commented Jul 21, 2010

awesome! :D

@rkh
Copy link
Author

rkh commented Jul 21, 2010

Note: this will be part of a group by, not a select and should give 200953 for 2010-01-01 (which is in the 53th week of 2009 per ISO-8601).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment