开发者

Find between with separated date fields (year,month,day)

I have the following dates in my table in separated fields. How can I write a query to show the values between two dates. For example: values between 2/1/2011 and 2/6/2011:

day         month            year          value 
--------------------------------------------------
2             6                2011         120
3             7                2011开发者_运维知识库         130
5             5                2011         100
6             1                2011         50


As others have said, my first suggestion would be to use Date. Or if you need more detailed information than your example, Datetime or Timestamp with Time Zone.

But in case you actually have to work with this data, I think something like this should work, depending on your flavor of SQL:

SELECT value, CONVERT(DATE,CONCAT(CONCAT(CONCAT(CONCAT(day, "-"), month), "-"), year), 105) date FROM table_name where (2/1/2011) <= date and date <= (2/6/2011);

(with Oracle SQL, you can use to_date instead of convert and optionally use the || concatenation operator; with SQL server you have to use the + concatenation operator; with MySQL this should be right)

(2/1/2011) and (2/6/2011) could either be strings that you convert similar to the other convert, or inputted using a PreparedStatement or something like it as dates directly (this would be preferable).


I had the same scenario but with Month column displaying Month name . With slight modification on the given query i was able to fetch the data.

SELECT        *
FROM            Table_Name AS Tbl_Date
WHERE        (Year * 10000 + DATEPART(mm, CAST(Month + Year AS DATETIME)) * 100 + 1 
BETWEEN 20111101 AND 20121201)

Hope this will help


To convert to Date for easier comparisons without worrying about dmy or mdy, in a standard fashion:

 DATEADD(year, year-1900, DATEADD(month, month-1, DATEADD(day, day-1, 0)))

So, something like this. The safest date format to use is yyyymmdd (especially with SQL Server)

SELECT
  value,
  DATEADD(year, year-1900, DATEADD(month, month-1, DATEADD(day, day-1, 0))) AS realdate
FROM Mytable_name
WHERE
  '20110201' <= DATEADD(year, year-1900, DATEADD(month, month-1, DATEADD(day, day-1, 0))) 
  and
  DATEADD(year, year-1900, DATEADD(month, month-1, DATEADD(day, day-1, 0))) <= '20110206'


if you are using oracle database then you can use TO_DATE and TO_CHAR functions to achive this target...

as follow-

  select * from table_name 
  where to_date(day||month||year,'DDMMYYYY') 
  between &mindate and &maxdate

min date you can put 2-jan-2011 and max date as 2-jun-2011

I hope it should work for you :)


well i found the answer that i wanted thanks guys

SELECT Tbl_Date.Value,Tbl_Date.Year,Tbl_Date.Month,Tbl_Date.Day from Tbl_Date
where   ((Tbl_Date.Year*10000)+(Tbl_Date.Month*100)+Tbl_Date.Day)  between 110102 and 110602 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜