如何在SQL查询中选择时间戳的一部分 [英] How to select part of a Timestamp in a SQL Query

查看:896
本文介绍了如何在SQL查询中选择时间戳的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在正在使用的数据库中,我只想从特定的时间戳记"字段中选择年份.特别是,我希望从此数据库列中选择唯一年份.

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.

例如,如果"ModifyTimeStamp"字段中的所有时间戳记都来自2002年或2006年,那么我只想返回"2002"和"2006"的结果.如果这不可能,那么我会满意地得到一堆'2002'和'2006'的混合结果,并在以后进行解析.

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.

到目前为止,我只能进行的工作是"Select ModifyTimeStamp from Table"-我所有的解析尝试都失败了.我开始阅读有关SQL的extract命令的信息,但我相信它仅适用于PostgreSQL.

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.

任何建议,不胜感激!

编辑:得到了答案,非常感谢datagod和Marc.我一直在寻找的代码最终是:

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"

推荐答案

您没有指定要使用的RDBMS(数据库服务器),但是大多数数据库确实具有内置的日期处理功能:

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

  • MySQL/SQL Server:

  • MySQL/SQL Server:

select YEAR(modifytimestamp) from yourtable

  • Access/SQL Server:

  • Access/SQL Server:

    select DatePart(year, modifytimestamp) from yourtable
    

  • Oracle:

  • Oracle:

    select TO_CHAR(modifytimestamp, 'YYYY') from yourtable
    

  • 这篇关于如何在SQL查询中选择时间戳的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆