Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL Date Comparison With Month and Year in Separate Columns

I have a table (let’s call it MyData) that has some information and also stores a month and a year in separate columns but no day, so it looks like this:

SomeData1 SomeData2 Month Year SomeDataN…
1 2021
2 2021
3 2021
8 2022
12 2022
5 2023
7 2023

I need to get all data from March 2021 to today.

I am trying to convert the Month and Year column into a date while also adding 01 as the day portion of the date (the specific day does not matter since it is not even stored in the table). I then want to compare this converted date from the table to my required date of March 2021 (‘2021-03-01). I’m not even sure if it is necessary to add the day portion to either of these as well.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am really stuck and not sure how to do this. Maybe there is a simpler solution than converting into dates and comparing?

I’ve tried:

SELECT DATEFROMPARTS([Year], [Month], 01) AS DATE
               FROM dbo.MyData)

So now I have all the month/year columns in a date format but really not sure where to go from here.

I want to do something like

SELECT * FROM MyData
WHERE (SELECT DATEFROMPARTS([Year], [Month], 01) AS DATE
           FROM dbo.MyData)) > '2021-03-01'

Thanks in advance.

>Solution :

In your case the best solution is to combine two where condition like following.

SELECT [Data]
      ,[Month]
      ,[Year]
FROM [Test].[dbo].[Table]
WHERE ([Month] >= 3 AND [Year] = 2021) OR [Year] > 2021
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading