sql-servert-sql

How to get all the data and exclude just current month data?


I have a column of varchar datatype which contains data as shown here. I would need to populate the chart excluding the current month's data, and I need the rest of the months data.

How would we write the query to exclude current month data which is 202503?

YearMonth
---------
202503
202502
202501
202412
202411
202410
202409

Thank you and appreciate the help.


Solution

  • You just need to construct an integer matching the current month, using the date functions and some arithmetic.

    WHERE YearMonth <> YEAR(GETDATE()) * 100 + MONTH(GETDATE())
    

    If it's a varchar column you can use CONCAT.

    WHERE YearMonth <> CONCAT(YEAR(GETDATE()), MONTH(GETDATE()))
    

    Why you are storing dates in integer or varchar columns is another question, this should not be done.