Select records from start of month to current date

↘锁芯ラ 提交于 2019-12-20 04:36:44

问题


I'm trying to select records that were added to the database between the start of the current month and the current day - I more or less know how to get records from the current day, and within a specific time period - but how do I get it so it starts from the beginning of the current calendar month?


回答1:


DECLARE @sm DATETIME;
SET @sm = DATEADD(DAY, 1-DAY(GETDATE()), DATEDIFF(DAY, 0, GETDATE()));

SELECT columns 
    FROM dbo.foo 
    WHERE datetime_column >= @sm;



回答2:


WHERE YEAR([Date])=YEAR(GETDATE())
AND MONTH([Date])=MONTH(GETDATE())
AND DAY([Date])<=DAY(GETDATE())



回答3:


select *
from YourTable
where DateCol >= dateadd(month, datediff(month, 0, getdate()), 0)



回答4:


Basically what you're doing here is Getting the Month, appending '/01' and then appending the year. Casting it as a string to handle the appending, then casting it as a DateTime.

So it's a little bit more involved than doing any sort of date math, but it's readable I think.

DECLARE @firstOfMonth DATETIME
SET @firstOfMonth = CAST(CAST(DATEPART(mm, GetDate()) as varchar) + '/01/' + cast(DATEPART(yyyy, Getdate()) as varchar) as datetime)

WHERE DateToCheck BETWEEN @firstOfMonth and GetDate()



回答5:


WHERE DateToCheck > LAST_DAY(CURDATE()-INTERVAL 1 MONTH))

http://www.sqlfiddle.com/#!2/3d673/2/0



来源:https://stackoverflow.com/questions/7403390/select-records-from-start-of-month-to-current-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!