I want to be able to select all database rows where the month and year are the same as what I am searching for. Since the DATE field has year, month, and day, how do I search with year and month?
+5
A:
SELECT *
FROM tblTableName
WHERE Month(ColumnDate) = Month(MyDate)
AND Year(ColumnDate) = Year(MyDate)
TheTXI
2009-03-10 14:47:21
+3
A:
SELECT *
FROM myTable
WHERE ( YEAR(myfield) = '2009')
AND ( MONTH(myfield) = '1')
Chris Lively
2009-03-10 14:48:10
+1
A:
That would depend on what database backend you are using. IN SQl Server I would use
where year(datefield) = @year and month (datefield) - @month
to do this.
or you could build a where clause by creating a date range
where datefield between 20090101 and 20090201
HLGEM
2009-03-10 14:49:51
+2
A:
In MySQL:
SELECT *
FROM mytable
WHERE date >= STR_TO_DATE(CONCAT(EXTRACT(YEAR_MONTH FROM @mydate), '01'), '%Y%m%d')
AND date < STR_TO_DATE(CONCAT(EXTRACT(YEAR_MONTH FROM @mydate), '01'), '%Y%m%d') + INTERVAL 1 MONTH
This will efficiently use an index on the date
field.
Quassnoi
2009-03-10 15:02:54
+1 on being so..., well..., complete. This is the n'th post I see you making about SQL, it seems you eat SQL for breakfast.
Lieven
2009-03-10 15:51:12
Thanks :) I've really been writing SQL for a living for almost 10 years already :)
Quassnoi
2009-03-10 16:26:08
+3
A:
The most efficient is to create the start and end date of the range that you want, so that you compare the dates as a single value instead of extracting the year and month properties from each date.
Example:
select SomeField
from SomeTable
where SomeDate >= ? and SomeDate < ?
(Note that the first comparison is inclusive and the seond is exclusive.)
Create the start and end date to use as parameters: (example in C#)
DateTime start = new DateTime(date.Year, date.Month, 1)
DateTIme end = start.AddMonths(1);
Guffa
2009-03-10 15:06:46