SQL query for extracting year from a date

柔情痞子 提交于 2020-06-24 07:40:22

问题


I am trying to create a query that gets only the year from selected dates. I.e. select ASOFDATE from PSASOFDATE; returns 11/15/2012, but I want only 2012. How can I get only the year? I know the YEAR function can be used, but I'm not sure how.


回答1:


SELECT YEAR(ASOFDATE) FROM PASOFDATE

Editted: In anycase if your date is a String, let's convert it into a proper date format. And select the year out of it.

SELECT YEAR(STR_TO_DATE(ASOFDATE, '%d-%b-%Y')) FROM PSASOFDATE

Since you are trying Toad, can you check the following code:

SELECT EXTRACT (TO_DATE(YEAR, 'MM/DD/YY') FROM ASOFDATE) FROM PSASOFDATE;

Reference:




回答2:


This worked for me:

SELECT EXTRACT(YEAR FROM ASOFDATE) FROM PSASOFDATE;



回答3:


How about this one?

SELECT TO_CHAR(ASOFDATE, 'YYYY') FROM PSASOFDATE



回答4:


just pass the columnName as parameter of YEAR

SELECT YEAR(ASOFDATE) from PSASOFDATE;

another is to use DATE_FORMAT

SELECT DATE_FORMAT(ASOFDATE, '%Y') from PSASOFDATE;
  • SQLFiddle Demo

UPDATE 1

I bet the value is varchar with the format MM/dd/YYYY, it that's the case,

SELECT YEAR(STR_TO_DATE('11/15/2012', '%m/%d/%Y'));
  • SQLFiddle Demo

LAST RESORT if all the queries fail

use SUBSTRING

SELECT SUBSTRING('11/15/2012', 7, 4)
  • SQLFiddle Demo


来源:https://stackoverflow.com/questions/13455440/sql-query-for-extracting-year-from-a-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!