Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order By month and year in sql with sum

Tags:

sql

sql-server

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?

like image 244
Bruce Avatar asked Jun 24 '13 08:06

Bruce


People also ask

How do I get the order date of a year in SQL?

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) at the end.

What is the difference between order by date and order by month?

If you order by month , year separately, it will go in ascending order of month in alphabetical order (April before January). If you order by order date id will be ordered based on a date value which is of course ordered by month/year.

How to get the full name of the month in SQL?

There's a date function that will do that for us. A lot of people have never heard of it but it's called DATENAME and it returns the fully spelled out name of the month in whatever the current SQL Server language settings are. Here's an example of how it works with a GROUP BY and no sort (we're trying to just get totals for the year 2010):

How to get the month value from the date in SQL?

For this, some of the columns of the table from which the data is being required must contain the month value or date value from where the month can be retrieved. Month value can be retrieved from the date-time data typed column using the SQL function MONTH (). This is done mostly for building queries for reports.


1 Answers

Try this:

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)

Note you need to add any fields you are ordering by to the group by clause

like image 84
Bob Vale Avatar answered Oct 14 '22 06:10

Bob Vale