SQL在where子句中转换日期格式

时间:2020-09-19 00:57:56

标签: sql oracle datetime subquery where-clause

当尝试使用where exists子句连接两个表时,由于日期的时间部分,结果无法匹配。表1中的日期为2020-09-01 00:00:00,表2中的日期为2020-09-01 12:54:00

如何设置日期格式,使其仅基于YYYY-MM-DD

SELECT * 
FROM  table1 a 
WHERE exists (
    SELECT '1' 
    FROM table2 b 
    WHERE a.company = b.company 
        AND a.emp =b.emp AND a.account_date = b.account_date
    )

1 个答案:

答案 0 :(得分:2)

在Oracle中,您可以使用trunc()

SELECT * 
FROM table1 a 
WHERE exists (
    SELECT 1 
    FROM table2 b 
    WHERE 
        a.company = b.company 
        AND a.emp = b.emp 
        AND trunc(a.account_date) = trunc(b.account_date)
)

如下所示,通常更有效地表达日期条件:

WHERE
    ...
    AND b.account_date >= trunc(a.account_date) 
    AND b.account_date < trunc(a.account_date) + 1