【问题标题】:Sql query get month from datetimeSql查询从日期时间获取月份
【发布时间】:2013-07-31 23:03:07
【问题描述】:

我有一个包含发票和创建日期时间的数据库,我想根据每张发票的日期创建一个名称为月份的新列。我的意思是如果日期是 2013 年 1 月 15 日,我想在新专栏上有“一月”。 先谢谢了,我对sql知之甚少。

【问题讨论】:

标签: sql


【解决方案1】:

如果您的数据库是 MySQL,请尝试:

DATE_FORMAT(date, '%M')

【讨论】:

    【解决方案2】:

    对于 MS SQL Server 使用

    SELECT DATENAME(MONTH,invoiceDate)
    

    【讨论】:

      【解决方案3】:

      在甲骨文中:

      TO_CHAR(date, 'Month')
      

      【讨论】:

        【解决方案4】:

        从 datetime 对象中提取月份,然后在 CASE 语句中使用它。

        以此为基础

        select 
          case strftime('%m', date('now')) 
            when '01' then 'January' 
            when '02' then 'Febuary' 
            when '03' then 'March' 
            when '04' then 'April' 
            when '05' then 'May' 
            when '06' then 'June' 
            when '07' then 'July' 
            when '08' then 'August' 
            when '09' then 'September' 
            when '10' then 'October' 
            when '11' then 'November' 
            when '12' then 'December' else '' end
          as month 
        

        我建议复制表的架构,为该月添加另一列。然后使用以下语句。

        INSERT INTO TABLE newTable (col1, col2, col3, ..., colLast, colMonth)
        SELECT col1, col2, col3, ..., colLast, 
              case strftime('%m', date('now')) 
                when '01' then 'January' 
                when '02' then 'Febuary' 
                when '03' then 'March' 
                when '04' then 'April' 
                when '05' then 'May' 
                when '06' then 'June' 
                when '07' then 'July' 
                when '08' then 'August' 
                when '09' then 'September' 
                when '10' then 'October' 
                when '11' then 'November' 
                when '12' then 'December' else '' end
              as colMonth
        FROM oldTable;
        

        然后

        drop table oldTable;
        

        然后

        Some alter to change the name of the new table to the name of the old table.
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-09-07
          • 2019-02-02
          • 1970-01-01
          • 1970-01-01
          • 2011-04-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多