Finding the Number of Days of Months Within a Certain Date Range in SQL Server
Hello everybody,
In this article, I will try to give information about finding the number of days of the months within a certain date range in SQL Server.
In SQL Server, in some cases, you may want to find the number of days of the months within a certain date range.
You can easily do this using the code below.
DECLARE @baslamatarihi DATE = '2022-07-10';
DECLARE @bitistarihi DATE = '2022-09-10';
WITH sorgu
AS (SELECT DATEFROMPARTS(YEAR(@baslamatarihi), MONTH(@baslamatarihi), 1) ay_baslangic_gunu,
1 - DAY(@baslamatarihi) + DAY( CASE
WHEN @bitistarihi > EOMONTH(@baslamatarihi) THEN
EOMONTH(@baslamatarihi)
ELSE
@bitistarihi
END
) AS gun_sayisi
UNION ALL
SELECT DATEADD(MONTH, 1, ay_baslangic_gunu),
CASE
WHEN @bitistarihi > DATEADD(MONTH, 2, ay_baslangic_gunu) THEN
DAY(EOMONTH(DATEADD(MONTH, 1, ay_baslangic_gunu)))
ELSE
DAY(@bitistarihi)
END
FROM sorgu
WHERE DATEADD(MONTH, 1, ay_baslangic_gunu) <= @bitistarihi)
SELECT *
FROM sorgu;
When you run the above code, you will see a result similar to the one below.
As you can see, we have found the number of days of the months within a certain date range.
Good luck to everyone in business and life.