Xkid
Xkid

Reputation: 409

How to select just current month data in SQL?

I'm trying to make a query that makes me able to select just the data from the current month from a table, the date field that I'm using as reference is Datetime Type (e.g 2021-02-19 03:23:31), this field is called "Date". My try is this as follow:

Select * 
FROM CORP.T_LOGI_RN_Planeacion_Entregas 
Where Cast(CORP.T_LOGI_RN_Planeacion_Entregas.Date As Date) >= Cast(Month(getdate()) As Date)

It's not working, (im not pretty sure if I need to use "Cast" Actually) it throws me this error:

Cannot cast type int to date

But using something like this where I'm not specifying the Month, it works:

Select * 
FROM CORP.T_LOGI_RN_Planeacion_Entregas 
Where Cast(CORP.T_LOGI_RN_Planeacion_Entregas.Date As Date) >= Cast(getdate() As Date)

Any idea?

Thanks by the way and sorry if the solution is so obvious I'm little bit new on this, best regards.

Upvotes: 2

Views: 5880

Answers (1)

Ankit Bajpai
Ankit Bajpai

Reputation: 13509

Since you have not specified your DB Product but from your syntax It seems SQL Server. YOu can use MONTH function here -

Select *
FROM CORP.T_LOGI_RN_Planeacion_Entregas
Where MONTH(CORP.T_LOGI_RN_Planeacion_Entregas.Date) = MONTH(GETDATE())
  AND YEAR(CORP.T_LOGI_RN_Planeacion_Entregas.Date) = YEAR(GETDATE());

Upvotes: 3

Related Questions