How to select part of a Timestamp in a SQL Query

冷暖自知 提交于 2019-12-06 22:12:11

问题


In the DB I am working with, I want to select only the year from a specific TimeStamp field. In particular, I'm hoping to select the unique years from this database column.

For instance, if all of the timestamps in the field "ModifyTimeStamp" are either from the year 2002 or the year 2006, I would like returned simply a result of '2002' and '2006'. If this is impossible, I'd be content with getting a result of a bunch of '2002's mixed with '2006's and would parse it later.

All I've been able to get working so far is "Select ModifyTimeStamp from Table" - all my attempts to parse have failed. I started reading about the extract command for SQL, but I believe it's only for PostgreSQL.

Any advice greatly appreciated!

Edit: Got the answer, thanks a lot datagod and Marc. The code I was looking for ended up being:

"Select distinct YEAR(ModifyTimeStamp) from Table"


回答1:


You don't specify which RDBMS (database server) you're using, but most databases do have date handling functions built-in:

  • MySQL/SQL Server:

    select YEAR(modifytimestamp) from yourtable
    
  • Access/SQL Server:

    select DatePart(year, modifytimestamp) from yourtable
    
  • Oracle:

    select TO_CHAR(modifytimestamp, 'YYYY') from yourtable
    



回答2:


Try this

select distinct datepart(yy,TheDate) from YourTable


来源:https://stackoverflow.com/questions/5808732/how-to-select-part-of-a-timestamp-in-a-sql-query

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