UDF: Quarter

UDF: Date to Quarter

Description

A function to turn a DATE into the Quarter (e.g. “Q1-2020”).

CREATE OR REPLACE FUNCTION <DATASET>.quarter(dt DATE) RETURNS STRING AS
(
"Q"||format_date('%Q',dt)||"-"||
    extract(year from dt) 
);

Example (optional)

with data as (
    select dates from unnest(generate_date_array('2021-02-28', '2021-12-02', INTERVAL 3 month)) AS dates
)
select 
    dates,
    spotify.quarter(dates) quarter
from data
dates quarter
2021-02-28 Q1-2021
2021-05-28 Q2-2021
2021-08-28 Q3-2021
2021-11-28 Q4-2021