从DATE只选择年份?

时间:2015-05-17 19:04:33

标签: sql oracle

我有一些问题如下:

Insert into Employee_T (EmployeeID,
                        EmployeeName,
                        EmployeeAddress,
                        EmployeeCity,
                        EmployeeState,
                        EmployeeZip,
                        EmployeeDateHired,
                        EmployeeBirthDate,
                        EmployeeSupervisor) 
values ('123-44-345',
        'Phil Morris',
        '2134 Hilltop Rd',
        'Knoxville',
        'TN',
        null,
        to_timestamp('12-JUN-99','DD-MON-RR HH.MI.SSXFF AM'),
        to_timestamp('05-JAN-57','DD-MON-RR HH.MI.SSXFF AM'),
        '454-56-768');

我有一个家庭作业问题"哪些员工在1999年被聘用?"上面的大胆日期。

如何编写选择语句以仅选择年份,并忽略日期和月份?

SELECT * FROM EMPLOYEE_T
WHERE EMPLOYEEDATEHIRED = '***what should i put here?***';

3 个答案:

答案 0 :(得分:3)

你试过这个吗?

SELECT * FROM EMPLOYEE_T WHERE EXTRACT (YEAR FROM EmployeeDateHired) = 1999

答案 1 :(得分:1)

EXTRACT

根据SQL standard规范的要求,PostgresOracle提供EXTRACT功能。您传递YEARMONTH等选择器以检索日期时间值的这一方面。

SELECT EXTRACT ( YEAR FROM TIMESTAMP '2001-02-16 20:38:40' ) ;

结果:

2001

答案 2 :(得分:1)

如果对列进行EXTRACT之类的计算,优化程序将失去利用现有索引的机会。

获得一个可搜索的ARGument"您最好按原样使用该列:

WHERE EmployeeDateHired >= TIMESTAMP '1999-01-01 00:00:00'
  AND EmployeeDateHired <  TIMESTAMP '2000-01-01 00:00:00'

在Oracle中,您也可以使用DATE自动添加00:00:00

WHERE EmployeeDateHired >= DATE '1999-01-01'
  AND EmployeeDateHired <  DATE '2000-01-01'