Order By month and year in sql with sum

前端 未结 7 2136
说谎
说谎 2020-12-29 08:58

I have a stored procedure and the select statement is:

SELECT     { fn MONTHNAME(OrderDate) } AS MonthName, YEAR(OrderDate) AS Year, SUM(TotalValue) AS Profi         


        
7条回答
  •  有刺的猬
    2020-12-29 09:38

    Just add

    Order by max(OrderDate) 
    

    at the end.

    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)
    Order by max(OrderDate) 
    

    Now about how it works:

    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.

提交回复
热议问题