返回当年的所有 mySQL 记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13592005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 15:35:14  来源:igfitidea点击:

Return all mySQL Records for Current Year

mysql

提问by user1857692

In mySQL, I would like to return a count of the records that have a start_datewithin the current year (as in the year 2012, NOT within the last one year time period) and (as a separate query) a count of the records from the previous year (2011 in the case as it is now).

在 mySQL 中,我想返回start_date在当前年份(如 2012 年,而不是在过去一年时间段内)的记录计数和(作为单独的查询)来自前一年(现在是 2011 年)。

My start dates are stored thus: 2012-12-02. I am using PHP.

我的开始日期是这样存储的:2012-12-02. 我正在使用 PHP。

Help on how I would form these queries would be hugely appreciated.

非常感谢我将如何形成这些查询的帮助。

回答by pixeline

SELECT COUNT(*)
 FROM TABLE1
 WHERE YEAR(START_DATE) = YEAR(CURDATE()); 

回答by Yogendra Singh

You may want to use YEARfunction to get the YEAR from the date and use the same in comparison.

您可能希望使用YEAR函数从日期中获取 YEAR 并在比较中使用相同的内容。

 SELECT COUNT(*)
 FROM TABLE1
 WHERE YEAR(START_DATE) = 2012;

Separate query from previous year:

与上一年分开查询:

 SELECT COUNT(*)
 FROM TABLE1
 WHERE YEAR(START_DATE) = 2011;

To get the year wise counts:

要获得明智的年份计数:

 SELECT COUNT(b.YEAR), b.YEAR
 FROM TABLE1 AS a JOIN 
    (SELECT DISTINCT YEAR(START_DATE) AS YEAR from TABLE1) AS b
    ON YEAR(START_DATE) = b.YEAR
 GROUP BY b.YEAR;

回答by Barranka

Two suggestions:

两个建议:

You can filter your data using dates:

您可以使用日期过滤数据:

select count(*) from tbl where start_date >= '2012-01-01'

or

或者

select count(*) from tbl where start_date between '2012-01-01' and '2012-12-31'

Also, you can filter your data using the year()function:

此外,您可以使用以下year()功能过滤数据:

select count(*) from tbl where year(start_date) = 2012

Hope this helps you

希望这对你有帮助



If you are using PHP (or any other high level programming language), you can build your query string on runtime to fit your needs (e.g. To filter records from different years).

如果您使用 PHP(或任何其他高级编程语言),您可以在运行时构建查询字符串以满足您的需要(例如过滤不同年份的记录)。

To show the count of records with start_datebefore 2012, just change the whereconditions:

要显示start_date2012 年之前的记录数,只需更改where条件:

select... where year(start_date) < 2012

or

或者

select... where start_date < '2012-01-01'