Select records from start of month to current date

后端 未结 5 1313
别那么骄傲
别那么骄傲 2021-01-25 08:16

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 curren

相关标签:
5条回答
  • 2021-01-25 08:50

    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()
    
    0 讨论(0)
  • 2021-01-25 08:52
    select *
    from YourTable
    where DateCol >= dateadd(month, datediff(month, 0, getdate()), 0)
    
    0 讨论(0)
  • 2021-01-25 08:55
    WHERE YEAR([Date])=YEAR(GETDATE())
    AND MONTH([Date])=MONTH(GETDATE())
    AND DAY([Date])<=DAY(GETDATE())
    
    0 讨论(0)
  • 2021-01-25 09:05
    WHERE DateToCheck > LAST_DAY(CURDATE()-INTERVAL 1 MONTH))
    

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

    0 讨论(0)
  • 2021-01-25 09:13
    DECLARE @sm DATETIME;
    SET @sm = DATEADD(DAY, 1-DAY(GETDATE()), DATEDIFF(DAY, 0, GETDATE()));
    
    SELECT columns 
        FROM dbo.foo 
        WHERE datetime_column >= @sm;
    
    0 讨论(0)
提交回复
热议问题