SQL for Smarties | SQL Programming Style | Trees and Hierarchies in SQL | SQL Puzzles and Answers | Data and Databases


Thursday, April 12, 2007

Month Year Date Comparison

SQL Apprentice Question
am running into a slight issue with a month year comparison. I
wrote q SP thats user-input driven. User selects a Start Month, Start
Year and an End Month and End Year. The database that houses the
information has month and year columns.


Example:
Name Month Year


Me 1 2006
You 1 2006
Us 3 2005
He 5 2007
She 6 2005
It 7 2006
We 12 2005
They 11 2005


The query looks like this:


select cust.name, CASE rev.[month]
WHEN '01' THEN 'January'
WHEN '02' THEN 'February'
WHEN '03' THEN 'March'
WHEN '04' THEN 'April'
WHEN '05' THEN 'May'
WHEN '06' THEN 'June'
WHEN '07' THEN 'July'
WHEN '08' THEN 'August'
WHEN '09' THEN 'September'
WHEN '10' THEN 'October'
WHEN '11' THEN 'November'
WHEN '12' THEN 'December'
END AS [Month], rev.year
from rev
inner join cust ON rev.name = cust.name
where (rev.name = @ter) AND (rev.month >= @start_month) AND (rev.year


>= @start_year) AND (rev.month <= @end_month) AND (rev.year <=


@end_year)
group by blah blah blah
order by blay blah blah

This works great until they span years.
Example:
Start Month = 11
Start Year = 2005
End Month = 2
End Year = 2006


Any ideas on how to make this work?



Celko Answers
This design flaw is called attribute splitting. A date is a single
unit of information, but you have put it into multiple columns. We can
fake it for your current problem, but you need to learn to use
temproal data types in SQL -- this is not 1950's COBOL any more, which
is how you are writing code.

No comments: