【问题标题】:How to sort by month name如何按月份名称排序
【发布时间】:2019-02-25 01:17:22
【问题描述】:

我有这样的疑问:

SELECT MonthName(Month(Transaction_Date)), SUM(Sales)
FROM Sales
GROUP BY MonthName(Month(Transaction_Date))
ORDER BY MonthName(Month(Transaction_Date))

但结果不按日期排序。如何按月份名称排序:一月、二月、三月等?

【问题讨论】:

    标签: sql ms-access


    【解决方案1】:

    一种方法是将两者都包含在GROUP BY中:

    SELECT MonthName(Month(Transaction_Date)), SUM(Sales)
    FROM Sales
    GROUP BY MonthName(Month(Transaction_Date)), Month(Transaction_Date)
    ORDER BY Month(Transaction_Date);
    

    或者只是通过MONTH()聚合:

    SELECT MonthName(Month(Transaction_Date)), SUM(Sales)
    FROM Sales
    GROUP BY Month(Transaction_Date)
    ORDER BY Month(Transaction_Date);
    

    然后在聚合之后应用MONTHNAME()

    或者,如果Transaction_Dates 都来自同一年,则使用聚合函数:

    SELECT MonthName(Month(Transaction_Date)), SUM(Sales)
    FROM Sales
    GROUP BY MonthName(Month(Transaction_Date))
    ORDER BY MIN(Transaction_Date);
    

    请注意,您可能还希望在月份中包含年份 - 这是一种最佳做法,因为通常您不希望在同一月份混合来自不同年份的数据。

    【讨论】:

      【解决方案2】:

      按月份 number 而非月份 name 对结果进行排序,例如:

      SELECT MonthName(Month(Transaction_Date)), Sum(Sales)
      FROM Sales
      GROUP BY MonthName(Month(Transaction_Date)), Month(Transaction_Date)
      ORDER BY Month(Transaction_Date)
      

      【讨论】:

      • 错误:在第一种情况下,查询不包含指定的表达式 Month(Transaction_Date) 作为聚合函数的一部分。并且 Query 在第二种情况下不包含指定的表达式 Transaction_Date 作为聚合函数的一部分。
      【解决方案3】:

      按月份名称排序将按字母顺序排列,但如果您只是按 Month(transaction_date) ASC/DESC 排序,那么您的结果应该可以正确排序。

      SELECT MonthName(Month(Transaction_Date)), SUM(Sales)
      FROM Sales
      GROUP BY Month(Transaction_Date)
      ORDER BY Month(Transaction_Date)
      

      【讨论】:

      • 如果你能提供一个例子会让你的答案更好。
      【解决方案4】:

      我想您应该按交易日期订购。

         SELECT 
       MonthName(Month(Transaction_Date)) 
          As Month_Name , SUM(Sales)
          FROM Sales
         GROUP BY Month_Name
        ORDER BY Transaction_Date
      

      【讨论】:

        【解决方案5】:

        尝试使用此查询:

        SELECT MonthName(Month(Transaction_Date)), SUM(Sales)
        FROM Sales
        GROUP BY MonthName(Month(Transaction_Date))
        ORDER BY Transaction_Date ASC
        

        请注意:

        ASC - 用于从 A 到 Z 的升序

        DESC - 用于从 Z 到 A 的降序

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-04-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多