2

我在数据库中有数千行记录的这个 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

它会输出这个:

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

我的问题是我根本无法按降序输出它,所以它看起来像这样:

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

因此,非常感谢任何帮助。

4

3 回答 3

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
于 2012-10-18T18:49:01.563 回答
0

您需要DESC从 ORDER BY 子句中删除。由于 DESC,您的结果是完全相反的顺序!

于 2012-10-18T18:41:38.140 回答
0

要获得您指定的订单,仅包括您想要的返回结果中的日期,您需要删除 desc 并将日期过滤器添加到您的 where 子句。

如果您的过滤器正确,这也可以让您摆脱最重要的声明。

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%' 
    AND /* filter date range i.e. MONTH(mydatetime) > 9 AND YEAR(mydatetime) > 2011 */
  GROUP BY DATENAME(MM, mydatetime) + ' ' + CAST(DAY(mydatetime) AS VARCHAR(2))
    , MONTH(mydatetime)
    , DAY(mydatetime)
  ORDER BY MONTH(mydatetime) 
    , DAY(mydatetime) 
于 2012-10-18T18:43:30.797 回答