Query first of month with results and query current date and compare

  • Is there a way to query the first of month from a table and return that data, and also query current date  from the same table and compare the difference between the two dates?

    Not looking for range of data, just the two selected dates.

    As Example

    Date           City    State   Temp    Diff
    08/01/2022 Hico TX 103
    08/24/2022 Hico TX 83 20


    Thank you

     

     

    • This topic was modified 2 years, 4 months ago by  brian.cook.

    Retired Navy Chief Petty Officer, Consulting Systems Engineer, C# Programmer, SQL Beginner

  • Write your query, then in your where conditions use:

    ([Date] = CAST(GETDATE() as DATE) OR [Date] = DATEADD(month, DATEDIFF(month, 0, CAST(GETDATE() AS DATE)), 0))
  • Just get the two dates and use them in your where clause with IN()...

    DECLARE @today DATE = (SELECT GETDATE());

    DECLARE @firstOfMonth DATE = DATEADD(day, 1, EOMONTH(@today, -1))

    WHERE Date IN (@today,@firstOfMonth)

    Assumption: Date column is actually a DATE.

    If its datetime or datetime2, you might want to convert your variables to the proper data type to avoid implicit conversion.

  • Thanks,

    After I wrote this, I realized I had this one figured out.

    Sorry, too many days on the same project and keep getting stuff dumped on me to add or change.

     

    Appreciate the assist.

    Retired Navy Chief Petty Officer, Consulting Systems Engineer, C# Programmer, SQL Beginner

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply