本文介绍了按月和年在 sql 中使用总和排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个存储过程,select语句是:
I have a stored procedure and the select statement is:
SELECT { fn MONTHNAME(OrderDate) } AS MonthName, YEAR(OrderDate) AS Year, SUM(TotalValue) AS Profits
FROM [Order]
WHERE (YEAR(OrderDate) = @year)
GROUP BY { fn MONTHNAME(OrderDate) }, YEAR(OrderDate)
这显示了每个月的总和但我需要按月和年对结果进行排序,因为我的结果如下所示:
this shows the sum total for every month But I need to order the result by month and year coz my result shown like:
April 2013
February 2013
January 2013
June 2013
March 2013
May 2013
在这种情况下有什么解决方案?
What is the solution in such a case?
推荐答案
试试这个:
SELECT { fn MONTHNAME(OrderDate) } AS MonthName, YEAR(OrderDate) AS Year, SUM(TotalValue) AS Profits
FROM [Order]
WHERE (YEAR(OrderDate) = @year)
GROUP BY { fn MONTHNAME(OrderDate) }, MONTH(OrderDate), YEAR(OrderDate)
order by Year(orderDate),month(OrderDate)
请注意,您需要将排序依据的任何字段添加到 group by 子句中
Note you need to add any fields you are ordering by to the group by clause
这篇关于按月和年在 sql 中使用总和排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!