MS-SQL sort output in descending order

前端 未结 3 2054
情话喂你
情话喂你 2021-01-15 09:09

I have this MS-SQL query with thousands of row records in database:

SELECT DISTINCT TOP 7 DATENAME(MM, mydatetime) + \' \' + CAST(DAY(mydatetime) AS VA         


        
相关标签:
3条回答
  • 2021-01-15 09:19

    You need to remove the DESC from your ORDER BY clause. Your result is in exact reverse order because of DESC!

    0 讨论(0)
  • 2021-01-15 09:28

    For your actual requirement, you can use your current query as a derived table and order that result in the way you want:

    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
    
    0 讨论(0)
  • 2021-01-15 09:38

    To get the order you specify including only the dates you want in the return results you need to remove the desc and add a date filter to your where clause.

    That may also allow you to get rid of the top statement if your do your filter right.

    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) 
    
    0 讨论(0)
提交回复
热议问题