【发布时间】: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))
但结果不按日期排序。如何按月份名称排序:一月、二月、三月等?
【问题讨论】:
我有这样的疑问:
SELECT MonthName(Month(Transaction_Date)), SUM(Sales)
FROM Sales
GROUP BY MonthName(Month(Transaction_Date))
ORDER BY MonthName(Month(Transaction_Date))
但结果不按日期排序。如何按月份名称排序:一月、二月、三月等?
【问题讨论】:
一种方法是将两者都包含在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);
请注意,您可能还希望在月份中包含年份 - 这是一种最佳做法,因为通常您不希望在同一月份混合来自不同年份的数据。
【讨论】:
按月份 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) ASC/DESC 排序,那么您的结果应该可以正确排序。
SELECT MonthName(Month(Transaction_Date)), SUM(Sales)
FROM Sales
GROUP BY Month(Transaction_Date)
ORDER BY Month(Transaction_Date)
【讨论】:
我想您应该按交易日期订购。
SELECT
MonthName(Month(Transaction_Date))
As Month_Name , SUM(Sales)
FROM Sales
GROUP BY Month_Name
ORDER BY Transaction_Date
【讨论】:
尝试使用此查询:
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 的降序
【讨论】: