LookupValueID LookupTypeID LookupValue LookupType
------------- ------------ -------------------------------------------------- -------------------
2 2 1/1/2007 12:00:00 AM Date
2 2 2/1/2008 12:00:00 AM Date
2 2 3/1/2009 12:00:00 AM Date
2 2 1/1/2007 12:00:00 AM Date
2 2 2/1/2008 12:00:00 AM Date
2 2 3/1/2009 12:00:00 AM Date
2 2 1/1/2007 12:00:00 AM Date
2 2 2/1/2008 12:00:00 AM Date
3072 records found
So now that I have only dates in my resultset, I want to extract the month and the year...
--Simple Query 3
SELECT
a.[LookupValue]
,DATEPART(MONTH,CONVERT(SMALLDATETIME,a.[LookupValue])) AS MonthPart
,DATEPART(YEAR,CONVERT(SMALLDATETIME,a.[LookupValue])) AS YearPart
FROM
[dbo].[testTable1] a INNER JOIN
[dbo].[testTable2] b ON
a.[ID] = b.[ID] AND b.[LookupType] = 'Date'
LookupValue MonthPart YearPart
-------------------------------------------------- ----------- -----------
1/1/2007 12:00:00 AM 1 2007
2/1/2008 12:00:00 AM 2 2008
3/1/2009 12:00:00 AM 3 2009
1/1/2007 12:00:00 AM 1 2007
2/1/2008 12:00:00 AM 2 2008
3/1/2009 12:00:00 AM 3 2009
1/1/2007 12:00:00 AM 1 2007
3072 records found
This is where it starts to get interesting...
So at this point, I am thinking if I want to limit my results to only dates with the month of 1 and year of 2007, I am pretty much there....
SELECT
a.[LookupValue]
,DATEPART(MONTH,CONVERT(SMALLDATETIME,a.[LookupValue])) AS MonthPart
,DATEPART(YEAR,CONVERT(SMALLDATETIME,a.[LookupValue])) AS YearPart
FROM
[dbo].[testTable1] a INNER JOIN
[dbo].[testTable2] b ON
a.[ID] = b.[ID] AND b.[LookupType] = 'Date'
WHERE
DATEPART(MONTH,CONVERT(SMALLDATETIME,a.[LookupValue])) = 1 AND
DATEPART(YEAR,CONVERT(SMALLDATETIME,a.[LookupValue])) = 2007;
LookupValue MonthPart YearPart
-------------------------------------------------- ----------- -----------
Msg 295, Level 16, State 3, Line 1
Conversion failed when converting character string to smalldatetime data type.