How can I use SQL statements to calculate the first day of this month?
You can write as follows:
SELECT DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0);
According to the datediff definition of the date function, the second parameter is the start date and the third parameter is the end date. What does 0 mean here?
It seems that the date type is essentially a numerical value, so there is no error in writing 0 here. The question is, on which day is 0?
SELECT CAST(0 AS DATETIME)
The result is: 00:00:00. 000.
It turns out that 0 is the first year of SQL Server. Therefore,
SELECT DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0);
That is, first obtain the month from the first year of the month, and then use the first year + the month to get the date, that is, the first day of the month.
Similarly, Monday of this week is
SELECT DATEADD(wk, DATEDIFF(wk,0,GETDATE()),0);
To be more complex, How about Monday of the first week of this month?
-- Declare @ firstday datetime = dateadd (mm, datediff (mm, 0, getdate (), 0) on the first day of this month; -- declare @ sevenday datetime = dateadd (DD, 6, @ firstday); -- select dateadd (wk, datediff (wk, 0, @ sevenday );
Why is it 7th days?
If the first day of this month is Monday, the second day is Sunday, which is the same week;
For example, if the first day of this month is Sunday, the first day is Saturday, which spans one week. The first day of this month is the week of the first day;
Both extreme situations are taken into consideration. The others are more clear, that is, the Monday of the first week of this month must be in the week of the first day of this month.