Skip to content

Instantly share code, notes, and snippets.

@leighajarett
Created April 13, 2021 15:57
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save leighajarett/ba348798714d2dc3f520bd3acda6c140 to your computer and use it in GitHub Desktop.
Save leighajarett/ba348798714d2dc3f520bd3acda6c140 to your computer and use it in GitHub Desktop.
BigQuery Period to Date
include: "mybaseview.view.lkml"
#add fields onto my existing base view
view: +mybaseview {
parameter: timeframe {
view_label: "Period over Period"
type: unquoted
allowed_value: {
label: "Week to Date"
value: "Week"
}
allowed_value: {
label: "Month to Date"
value: "Month"
}
allowed_value: {
label: "Quarter to Date"
value: "Quarter"
}
allowed_value: {
label: "Year to Date"
value: "Year"
}
default_value: "Quarter"
}
# To get start date we need to get either first day of the year, month or quarter
dimension: first_date_in_period {
view_label: "Period over Period"
type: date
hidden: no
sql: DATE_TRUNC(CURRENT_DATE(), {% parameter timeframe %});;
}
#Now get the total number of days in the period
dimension: days_in_period {
view_label: "Period over Period"
type: number
hidden: no
sql: DATE_DIFF(CURRENT_DATE(),${first_date_in_period}, DAY) ;;
}
#Now get the first date in the prior period
dimension: first_date_in_prior_period {
view_label: "Period over Period"
type: date
hidden: no
sql: DATE_TRUNC(DATE_ADD(CURRENT_DATE(), INTERVAL -1 {% parameter timeframe %}),{% parameter timeframe %});;
}
#Now get the last date in the prior period
dimension: last_date_in_prior_period {
view_label: "Period over Period"
type: date
hidden: no
sql: DATE_ADD(${first_date_in_prior_period}, INTERVAL ${days_in_period} DAY) ;;
}
# Now figure out which period each date belongs in (update with your own date dimension that you want to leverage)
dimension: period_selected {
view_label: "Period over Period"
type: string
sql:
CASE
WHEN ${my_date} >= ${first_date_in_period}
THEN 'This {% parameter timeframe %} to Date'
WHEN ${my_date} >= ${first_date_in_prior_period}
AND ${my_date} <= ${last_date_in_prior_period}
THEN 'Prior {% parameter timeframe %} to Date'
ELSE NULL
END ;;
}
}
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment