简体   繁体   English

按月/年计算总条目数的 SQL 查询

[英]SQL Query to Count total entries by Month/Year

I am trying to count the total number of entries in my SQL table for each month.我正在尝试计算每个月在我的 SQL 表中的条目总数。

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任何帮助都会很棒

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).除了group by子句之外,您的查询看起来不错,它指的是查询中不存在的列别名(这是语法错误)。

Consider:考虑:

Select
    DATE_FORMAT(`date`,'%M %Y') MontnameYear,
    COUNT(*) counter
FROM table1
GROUP BY DATE_FORMAT(`date`,'%M %Y')
ORDER by MIN(`date`)

Demo on DB FIddle : DB Fiddle上的演示

MontnameYear  | counter
:------------ | ------:
January 2019  |       2
February 2019 |       1
April 2019    |       1
May 2019      |       1
July 2019     |       1

Side notes: your sample script has flaws:旁注:您的示例脚本有缺陷:

  • it is mandatory to give a length to a varchar column (say, varchar(10) )必须为varchar列指定长度(例如varchar(10)
  • strings such as job A must be surrounded with single quotes字符串,例如job A必须用单引号括起来

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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