SQL query for extracting year from a date

前端 未结 5 911
忘了有多久
忘了有多久 2021-02-04 12:17

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

5条回答
  •  一整个雨季
    2021-02-04 12:42

    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

提交回复
热议问题