MS-SQL排序输出按降序排列

cra*_*xxx 2 sql-server coldfusion

我有这个MS-SQL查询在数据库中有数千行记录:

SELECT DISTINCT TOP 7 DATENAME(MM, mydatetime) + ' ' + CAST(DAY(mydatetime) AS VARCHAR(2)) as thedate
    , MONTH(mydatetime)
    , DAY(mydatetime)
    , COUNT(Page) as totalcount
    , count(DISTINCT Page) as visitors
  FROM someTable
  WHERE Page LIKE '%AEC%'
  GROUP BY DATENAME(MM, mydatetime) + ' ' + CAST(DAY(mydatetime) AS VARCHAR(2))
    , MONTH(mydatetime)
    , DAY(mydatetime)
  ORDER BY MONTH(mydatetime) DESC
    , DAY(mydatetime) DESC
Run Code Online (Sandbox Code Playgroud)

它将输出:

thedate     | totalcount | visitors
-----------------------------------
October 17  |     4      |    1
October 15  |     1      |    1
October 12  |     1      |    1
October 3   |     3      |    3
October 2   |     42     |    22
September 28|     2      |    1
September 21|     14     |    10
Run Code Online (Sandbox Code Playgroud)

我的问题是我不能按降序输出它,所以它看起来像这样:

thedate     | totalcount | visitors
-----------------------------------
September 21|     14     |    10
September 28|     2      |    1
October 2   |     42     |    22
October 3   |     3      |    3
October 12  |     1      |    1
October 15  |     1      |    1
October 17  |     4      |    1
Run Code Online (Sandbox Code Playgroud)

所以任何帮助都非常感谢.

Lam*_*mak 9

对于您的实际需求,您可以将当前查询用作派生表,并按照您希望的方式进行排序:

SELECT *
FROM (  SELECT DISTINCT TOP 7 DATENAME(mm, mydatetime) + ' ' 
                              + CAST(DAY(mydatetime) AS VARCHAR(2)) AS thedate, 
                              MONTH(mydatetime)                     AS theMonth, 
                              DAY(mydatetime)                       AS theDay, 
                              COUNT(page)                           AS totalcount, 
                              COUNT(DISTINCT page)                  AS visitors 
        FROM   sometable 
        WHERE  page LIKE '%AEC%' 
        GROUP  BY DATENAME(mm, mydatetime) + ' ' 
                  + CAST(DAY(mydatetime) AS VARCHAR(2)), 
                  MONTH(mydatetime), 
                  DAY(mydatetime) 
        ORDER  BY MONTH(mydatetime) DESC, 
                  DAY(mydatetime) DESC) A
ORDER BY theMonth, theDay
Run Code Online (Sandbox Code Playgroud)