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) at the end.
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.
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):
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With