简体   繁体   中英

How to write Stored procedure to get the group data of a month and year

How to Create stored proc that gives totals grouped for month and year

sale tablename

year week  date      value
2008 4    2008-01-21  50
2008 5    2008-02-22  25
2008 6    2008-02-23  30

It can be done using a simple SQL:

SELECT to_char(date,'MON-YYYY'), SUM(VALUE) FROM SALE
GROUP BY to_char(date,'MON-YYYY');

Try this

SELECT year,MONTH(date) AS [Month], SUM(value) AS [value] FROM sale 
GROUP BY year,MONTH(date)

Here is a full stored procedure code with parameters and example on how to run this.

CREATE PROCEDURE dbo.GetTotalByDate
(
    @StartDate datetime,
    @EndDate datetime
)
AS 
BEGIN
    SELECT S.year as [Year],
    MONTH(S.date) as [Month],
    SUM(S.Value) as [Value]
    FROM Sale S
    WHERE S.date BETWEEN @StartDate and @EndDate
    GROUP BY S.year, MONTH(S.date) 
    ORDER BY [Year], [Month] 
END


EXEC dbo.GetTotalByDate @StartDate = '01/01/2013', @EndDate = '01/01/2014'

Try this

CREATE PROCEDURE dbo.GetTotalAmount
AS 
BEGIN
    SELECT DATEPART(YEAR, date)as [Year],
    MONTH(date) as [Month],
    SUM(Value) as [Value]
    FROM Sale 
    GROUP BY DATEPART(YEAR, date), MONTH(date) 
END

EXEC dbo.GetTotalAmount

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM