patternsqlMinor
Get counts grouped by month and year
Viewed 0 times
yeargetgroupedmonthandcounts
Problem
I am trying to report on data in e-email messaging system and wanted to have SQL tally counts by
This is what I have but its limiting in that I need to manually change years. Can this be upgraded to output for all dates in the table in this
Removing the year would clump all the months over may years together and distort the data. I am looking to get the counts from that particular
month/year.SELECT YEAR(crdate) AS y,
MONTH(crdate) AS m,
COUNT(*) AS tally
FROM MESSAGE
WHERE YEAR(crdate) = 2012
AND SUBJECT <> 'Welcome' --exclude default messages
GROUP BY
YEAR(crdate),
MONTH(crdate)This is what I have but its limiting in that I need to manually change years. Can this be upgraded to output for all dates in the table in this
month/year format?Removing the year would clump all the months over may years together and distort the data. I am looking to get the counts from that particular
month/year.Solution
Wrap this up in a stored procedure then:
This will allow you to specify the year you want to get the data from in the call. I.e.
This is what I have but its limiting in that I need to manually change years.
Given your requirements there is no way to do this automatically.
CREATE PROCEDURE GetYearCounts
@year INT
AS
SELECT YEAR(crdate) AS y,
MONTH(crdate) AS m,
COUNT(*) AS tally
FROM MESSAGE
WHERE YEAR(crdate) = @year
AND SUBJECT <> 'Welcome' --exclude default messages
GROUP BY
YEAR(crdate),
MONTH(crdate);
GOThis will allow you to specify the year you want to get the data from in the call. I.e.
EXEC GetYearCounts @year = 2012;
GOThis is what I have but its limiting in that I need to manually change years.
Given your requirements there is no way to do this automatically.
Code Snippets
CREATE PROCEDURE GetYearCounts
@year INT
AS
SELECT YEAR(crdate) AS y,
MONTH(crdate) AS m,
COUNT(*) AS tally
FROM MESSAGE
WHERE YEAR(crdate) = @year
AND SUBJECT <> 'Welcome' --exclude default messages
GROUP BY
YEAR(crdate),
MONTH(crdate);
GOEXEC GetYearCounts @year = 2012;
GOContext
StackExchange Database Administrators Q#33975, answer score: 9
Revisions (0)
No revisions yet.