【问题标题】:How to sort the the sql table considering the month an year column考虑到月份和年份列,如何对 sql 表进行排序
【发布时间】:2015-08-10 16:16:18
【问题描述】:

我有一个年份列,其中包含字符串值,例如 2015、2014、2013、2012 等。月份列显示字符串值,例如一月、二月、...十二月。考虑到年份和月份列,我需要运行一个对表格进行排序的选择。任何人都可以提供一些输入吗?是否有任何系统程序可以轻松完成。

我想要基于年份和月份降序的输出。

【问题讨论】:

  • 这是mysql还是sqlserver?

标签: mysql sql-server


【解决方案1】:

你可以这样做:

order by cast(year as int) desc
         ,case when month = 'January' then 1
               when month = 'February' then 2
               ....
               when month = 'December' then 12
          end desc

【讨论】:

    【解决方案2】:

    试试这个

    ORDER BY CAST(month+year AS DATE) DESC
    

    【讨论】:

      【解决方案3】:

      这样试试

       DECLARE @table TABLE
            (
               year  VARCHAR(10),
               month VARCHAR(20)
            )
      
          INSERT INTO @table
          VALUES      ('2015',
                       'January'),
                      ('2015',
                       'March'),
                      ('2015',
                       'February'),
                      ('2015',
                       'April'),
                      ('2015',
                       'May'),
                      ('2014',
                       'January'),
                      ('2014',
                       'February'),
                      ('2014',
                       'March'),
                      ('2014',
                       'May'),
                      ('2014',
                       'April'),
                      ('2016',
                       'January'),
                      ('2016',
                       'February'),
                      ('2016',
                       'March'),
                      ('2016',
                       'May'),
                      ('2016',
                       'April')
      
              SELECT *
          FROM   @table
          ORDER  BY CONVERT(INT, year) desc,
                    Datepart(mm, Cast(month + ' 1900' AS DATETIME)) desc 
      

      【讨论】:

        【解决方案4】:

        您需要将月份名称翻译成数字,以便使用翻译参考表并存储值

         jan-1,feb-2,march-3 like wise
        

        那就试试吧

        SELECT * FROM tblName ORDER BY yearField DESC, monthField DESC  
        

        【讨论】:

          猜你喜欢
          • 2023-04-01
          • 2015-05-20
          • 1970-01-01
          • 1970-01-01
          • 2018-11-24
          • 1970-01-01
          • 2019-12-06
          • 2012-06-28
          • 2021-11-26
          相关资源
          最近更新 更多