繁体   English   中英

在分隔日期字段(年、月、日)之间查找

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

我在分隔字段中的表格中有以下日期。 如何编写查询以显示两个日期之间的值。 例如:2/1/2011 和 2/6/2011 之间的值:

day         month            year          value 
--------------------------------------------------
2             6                2011         120
3             7                2011         130
5             5                2011         100
6             1                2011         50

我有同样的情况,但月份列显示月份名称。 通过对给定查询的轻微修改,我能够获取数据。

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

希望这会有所帮助

正如其他人所说,我的第一个建议是使用日期。 或者,如果您需要比您的示例更详细的信息,Datetime 或 Timestamp with Time Zone。

但如果你真的必须使用这些数据,我认为这样的事情应该可以工作,这取决于你对 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) 和 (2/6/2011) 可以是与其他转换类似的字符串,也可以是使用 PreparedStatement 或类似的东西直接作为日期输入的字符串(这会更好)。

要转换为 Date 以便于比较而不用担心 dmy 或 mdy,以标准方式:

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

所以,像这样的东西。 最安全的日期格式是yyyymmdd (尤其是 SQL 服务器)

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'

如果您使用的是 oracle 数据库,那么您可以使用 TO_DATE 和 TO_CHAR 函数来实现此目标...

如下-

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

最小日期你可以把 2-jan-2011 和最大日期作为 2-jun-2011

我希望它对你有用:)

好吧,我找到了我想要的答案谢谢大家

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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM