Reputation: 405
I am trying to count the total number of entries in my SQL table for each month.
CREATE TABLE table1
(`ID` int, `date` date, `job` varchar)
;
INSERT INTO table1
(`ID`, `date`, `job`)
VALUES
(1, '2019-01-01', job A),
(2, '2019-01-03', job B),
(3, '2019-02-02', job C),
(4, '2019-04-05', job D),
(5, '2019-05-03', job E),
(6, '2019-07-07', job F)
;
Select
DATE_FORMAT(`date`,'%M %Y') MontnameYear,
COUNT(job) counter
FROM table1
GROUP BY DATE_FORMAT(`date`,'%M %Y')
ORDER by mdate;
I have tried various different variations of the above but nothing that gets me a count for each month. I have a feeling that I am missing something obvious but cant see it :-(
Any help would be great
Upvotes: 0
Views: 358
Reputation: 222472
You query looks fine, apart from the group by
clause, that refers to a column alias that does not exist in the query (that's a syntax error).
Consider:
Select
DATE_FORMAT(`date`,'%M %Y') MontnameYear,
COUNT(*) counter
FROM table1
GROUP BY DATE_FORMAT(`date`,'%M %Y')
ORDER by MIN(`date`)
MontnameYear | counter :------------ | ------: January 2019 | 2 February 2019 | 1 April 2019 | 1 May 2019 | 1 July 2019 | 1
Side notes: your sample script has flaws:
varchar
column (say, varchar(10)
)job A
must be surrounded with single quotesUpvotes: 2