cancel
Showing results forย 
Search instead forย 
Did you mean:ย 
Data Engineering
Join discussions on data engineering best practices, architectures, and optimization strategies within the Databricks Community. Exchange insights and solutions with fellow data engineers.
cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

Converting TSQL datepart(week) to Databricks SQL

Shahfik
New Contributor II

Hi!

I'm converting an existing TSQL script into Databricks SQL.

In TSQL, the below script returns 1
select datepart(WEEK,'2022-01-01')

In Databricks SQL, then below script returns 52.

select date_part('week','2022-01-01')
 
Does Databricks SQL have something equivalent where Jan 1 is the first week of the year? Thank you in advance.
2 REPLIES 2

Amine
Databricks Employee
Databricks Employee

The implementations of date_part and weekofyear functions follow the week numbering specs in ISO 8601. Check the following Wikipedia page for the rules concerning week 52 and 53.

The function returns the value '1' if the day is January 1st and falls on a Monday through Thursday.

Screenshot 2023-08-25 at 12.24.37.png

TimFrazer
New Contributor II

This worked for me.

SELECT
  your_date_column,
  CASE
    WHEN DAYOFYEAR(your_date_column) <= 7 THEN 'Week 1'
    ELSE 'Week ' || CAST(CEIL((DAYOFYEAR(your_date_column) - 7) / 7.0) + 1 AS STRING)
  END AS WeekNumber
FROM your_date_table;

Connect with Databricks Users in Your Area

Join a Regional User Group to connect with local Databricks users. Events will be happening in your city, and you wonโ€™t want to miss the chance to attend and share knowledge.

If there isnโ€™t a group near you, start one and help create a community that brings people together.

Request a New Group