如何查询具有笨拙日期格式的列

时间:2010-12-22 00:39:16

标签: sql pervasive-sql

以下是格式化日期的方式:

 XXXXXX001221

这个日期是12月21日

如果我想使用CURDATE()函数获取昨天的条目,我该如何做?

2 个答案:

答案 0 :(得分:1)

如果你只是在做一个月 - (索引是基于CURDATE()的字符串格式,即YYYY-MM-DD):

SELECT * FROM table_name
WHERE date_field LIKE
  CONCAT('%', SUBSTR(DATE_SUB(CURDATE(), INTERVAL 1 DAY) FROM 6 FOR 2),
              SUBSTR(DATE_SUB(CURDATE(), INTERVAL 1 DAY) FROM 9 FOR 2));

使用EXTRACT()的替代方法:

SELECT * FROM table_name
WHERE date_field LIKE
  CONCAT('%', EXTRACT(MONTH FROM DATE_SUB(CURDATE(), INTERVAL 1 DAY)),
              EXTRACT(DAY FROM DATE_SUB(CURDATE(), INTERVAL 1 DAY)));




一年也是:

SELECT * FROM table_name
WHERE date_field LIKE
  CONCAT('%', SUBSTR(DATE_SUB(CURDATE(), INTERVAL 1 DAY) FROM 3 FOR 2),
              SUBSTR(DATE_SUB(CURDATE(), INTERVAL 1 DAY) FROM 6 FOR 2),
              SUBSTR(DATE_SUB(CURDATE(), INTERVAL 1 DAY) FROM 9 FOR 2));


SELECT * FROM table_name
WHERE date_field LIKE
  CONCAT('%', EXTRACT(YEAR FROM DATE_SUB(CURDATE(), INTERVAL 1 DAY)),
              EXTRACT(MONTH FROM DATE_SUB(CURDATE(), INTERVAL 1 DAY)),
              EXTRACT(DAY FROM DATE_SUB(CURDATE(), INTERVAL 1 DAY)));




编辑:代替WHERE date_field LIKE ...,您可以使用代码中提到的WHERE RIGHT(date_field, 6) = ...来回答:

SELECT * FROM table_name
WHERE RIGHT(date_field, 4) =
  CONCAT(EXTRACT(MONTH FROM DATE_SUB(CURDATE(), INTERVAL 1 DAY)),
         EXTRACT(DAY FROM DATE_SUB(CURDATE(), INTERVAL 1 DAY)));

SELECT * FROM table_name
WHERE RIGHT(date_field, 6) =
  CONCAT(EXTRACT(YEAR FROM DATE_SUB(CURDATE(), INTERVAL 1 DAY)),
         EXTRACT(MONTH FROM DATE_SUB(CURDATE(), INTERVAL 1 DAY)),
         EXTRACT(DAY FROM DATE_SUB(CURDATE(), INTERVAL 1 DAY)));

注意:您也可以使用变量来保存计算DATE_SUB(CURDATE(),INTERVAL 1 DAY)。

SET @yesterday = DATE_SUB(CURDATE(), INTERVAL 1 DAY);
SELECT ...

答案 1 :(得分:0)

尝试类似:

SELECT * FROM table WHERE RIGHT(date_col, 6) = (SELECT CONVERT(VARCHAR(6), GETDATE()-1, 12) AS [YYMMDD])