我有这样的查询:
SELECT MonthName(Month(Transaction_Date)), SUM(Sales)
FROM Sales
GROUP BY MonthName(Month(Transaction_Date))
ORDER BY MonthName(Month(Transaction_Date))
但是结果未按日期排序。如何按月份名称排序:一月,二月,三月等?
答案 0 :(得分:1)
按月份数字(而不是月份名称)对结果进行排序,例如:
SELECT MonthName(Month(Transaction_Date)), Sum(Sales)
FROM Sales
GROUP BY MonthName(Month(Transaction_Date)), Month(Transaction_Date)
ORDER BY Month(Transaction_Date)
答案 1 :(得分: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_Date
都来自同一年,则使用汇总函数:
SELECT MonthName(Month(Transaction_Date)), SUM(Sales)
FROM Sales
GROUP BY MonthName(Month(Transaction_Date))
ORDER BY MIN(Transaction_Date);
请注意,您可能还希望将年份和月份都包括在内-这是一种最佳做法,因为通常您不想在同一个月中混合不同年份的数据。
答案 2 :(得分:1)
按月份名称排序将是字母顺序,但是如果您仅按Month(transaction_date)ASC / DESC进行排序,则应该正确地对结果进行排序。
SELECT MonthName(Month(Transaction_Date)), SUM(Sales)
FROM Sales
GROUP BY Month(Transaction_Date)
ORDER BY Month(Transaction_Date)
答案 3 :(得分:0)
尝试使用此查询:
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阶
答案 4 :(得分:0)
我想您应该按交易日期订购。
SELECT
MonthName(Month(Transaction_Date))
As Month_Name , SUM(Sales)
FROM Sales
GROUP BY Month_Name
ORDER BY Transaction_Date