0
I need an SQL function to get data grouped by month.
I have in the column CPCCodeID
codes (ex: 512456). I need to count and group by the first two digits. I need it separated for months (!!!) and to make it easier I made this loop that goes through all the months and groups the way I need it.
At this moment I have arrived at this solution:
USE CCILCDatabase;
GO
DECLARE @mes int;
SET @mes = 1;
WHILE (select @mes) <= 12
BEGIN
SELECT LEFT(CONVERT(VARCHAR(10),[CPCCodeID]),2), COUNT(*)
FROM PublicContestCPC
where YEAR(DateCreated) = '2017' AND MONTH(DateCreated) = (select @mes)
GROUP BY LEFT(CONVERT(VARCHAR(10),[CPCCodeID]),2)
ORDER BY LEFT(CONVERT(VARCHAR(10),[CPCCodeID]),2)
SET @mes += 1;
END
PRINT @mes;
I know you can change this code to not use the loop
, but my knowledge of SQL is somewhat limited. I wanted to use this to export to an Excel sheet, but the way it’s implemented doesn’t work.
What’s the need for this?
LEFT(CONVERT(VARCHAR(10),[CPCCodeID]),2)
. Perhaps I can help you!– Marconi
I recommend reading: DISTINCT and GROUP BY, what is the difference between the two statements?
– Marconi
I’ve already added more details of what I intend to do.
– ihavenokia
That alone would solve the problem?
SELECT LEFT(CONVERT(VARCHAR(10),[CPCCodeID]),2), COUNT(*)
FROM PublicContestCPC
where YEAR(DateCreated) = '2017' AND MONTH(DateCreated) <=@mes
GROUP BY LEFT(CONVERT(VARCHAR(10),[CPCCodeID]),2)
ORDER BY LEFT(CONVERT(VARCHAR(10),[CPCCodeID]),2)
– Marconi
That gives me the results I want, but it’s only a month
– ihavenokia
puts the month in the result:
SELECT LEFT(CONVERT(VARCHAR(10),[CPCCodeID]),2), mes, COUNT(*) FROM PublicContestCPC where YEAR(DateCreated) = '2017' AND MONTH(DateCreated) <=@mes GROUP BY LEFT(CONVERT(VARCHAR(10),[CPCCodeID]),2),mes ORDER BY LEFT(CONVERT(VARCHAR(10),[CPCCodeID]),2)
– Marconi