0

To get the last day of a semester, I am using the below query:

select dateadd(quarter, datediff(quarter, 0, @mydate) / 2 * 2 + 2, -1)

I want to use a similar approach to get the first day of half year based on a given date.

For example, if my date is 5th of March 2024, then the SQL should return 1st of January 2024.
And if my date is 15th of November 2024. then the SQL should return 1st July 2024. Any help please?

1
  • 2
    Use a calendar table instead of trying to calculate dates on the fly. The expression you used may work but can't take advantage of any indexes. Using it for filtering and grouping quickly results in unreadable queries. With a calendar table though, all you have to do is to use the Semester, Quarter or HalfYear field Commented Feb 26, 2024 at 9:02

1 Answer 1

2

The simplest method, in modern versions of SQL Server, would be to just use DATE_BUCKET:

SELECT DATE_BUCKET(MONTH, 6, GETDATE());

If you aren't on 2022+, you'll need to use the "old" DATEADD/DATEDIFF method. The /6 * 6 makes use of integer division. So, for example, 10 / 6 * 6 = (10 / 6) * 6 = (~1.66 ≈ 1) * 6 = 1 * 6 = 6

SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) / 6 * 6,0);
Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately the version which I am using does not have DATE_BUCKET.
I've added the "old" way, but you should really denote the version you are using in your question, @Alis . This means you don't get solutions you can't use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.