按MSSQL中的不同日期排序

时间:2015-12-22 09:29:26

标签: sql sql-server datetime

我尝试使用月份名称进行排序,当我在数字中使用它时,一切正常,但是当我尝试做出像这样的选择时

SELECT DISTINCT 
CONVERT(nvarchar(50), DATENAME(m, date) + ', ' + DATENAME(yyyy,date)) as date 
From MyTable

在我的输出中,我有类似的东西

August, 2015
July, 2015
September, 2015

如何按月分类,而不是按字母顺序排序?

我尝试添加order by date但没有任何结果。 输出格式应该是这样的。

3 个答案:

答案 0 :(得分:2)

只需将查询嵌入子查询中,并选择月份编号以及字符串:

DECLARE @t TABLE ( [date] DATE )

INSERT  INTO @t
VALUES  ( '20150701' ),
        ( '20150701' ),
        ( '20150801' ),
        ( '20150901' )

SELECT  [date]
FROM    ( SELECT DISTINCT
                    CONVERT(NVARCHAR(50), DATENAME(m, [date]) + ', '
                    + DATENAME(yyyy, [date])) AS [date] ,
                    YEAR([date]) AS y ,
                    MONTH([date]) AS m
          FROM      @t
        ) t
ORDER BY t.y, t.m

输出:

date
July, 2015
August, 2015
September, 2015

答案 1 :(得分:2)

您应该在所选列表中设置必须具有的订单条件。 尝试这样的事情:

SELECT DISTINCT 
    CONVERT(nvarchar(50), DATENAME(m, date) + ', '   + DATENAME(yyyy,date)) as date, 
    year(date) * 100 + month(date) as ordercrit
From 
    MyTable 
order by 
    ordercrit

如果您希望在排序中考虑ordercrityear也应包含January, 2014 February, 2014 January, 2015 May, 2015 January, 2016

public void onClick(View v) {
            Toast.makeText(MainActivity.this,"Button Clicked",Toast.LENGTH_LONG).show();
           InputMethodManager imm = (InputMethodManager) getSystemService(MainActivity.INPUT_METHOD_SERVICE);
           imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);            
        }

答案 2 :(得分:1)

另一种方法

DECLARE @t TABLE ( [date] DATE )

INSERT  INTO @t
VALUES  ( '20150701' ),
        ( '20150701' ),
        ( '20150801' ),
        ( '20150901' )

SELECT DATE FROM 
(
SELECT DISTINCT
       CONVERT(NVARCHAR(50), DATENAME(M, DATE) + ', ' + DATENAME(YYYY,DATE)) AS DATE  
FROM      @T
) AS T        ORDER BY CAST(DATE AS DATETIME)