[英]Select all MySQL data, count records by month, year not working correctly
I have a database table with a list of IP addresses each with a datetime
column, which in basic is something like this example: 我有一个带有IP地址列表的数据库表,每个IP地址都有一个
datetime
列,从datetime
上来说,该示例类似于以下示例:
ip_address | date_first_viewed
192.122.42.2 2015-12-23 14:03:10
183.123.13.4 2015-12-23 02:11:10
193.311.31.6 2015-11-10 12:29:00
I am trying to select, count and group the data according to Month, Year so it would show as: 我正在尝试根据月,年对数据进行选择,计数和分组,因此它将显示为:
(2015, 12) 2
(2015, 11) 1
Here is my current query I am using although this isn't returning any dates whatsoever? 这是我当前正在使用的查询,尽管它不返回任何日期?
$sql8 = "SELECT COUNT(ip_address) as count, EXTRACT(YEAR_MONTH FROM date_first_viewed) as date
FROM `all_website_stats`
GROUP BY EXTRACT(YEAR_MONTH FROM date_first_viewed)";
Your SQL looks good. 您的SQL看起来不错。 Just escape the reserved words
count
and date
with backticks to avoid issues. 刚刚逃出保留字
count
和date
与反引号,以避免问题。 To get the date in the format you want, you might try this query, which just concatenates the additional characters you want for formatting: 要以所需的格式获取日期,您可以尝试以下查询,该查询只是将您要格式化的其他字符连接起来:
SELECT CONCAT('(', YEAR(date_first_viewed), ', ', MONTH(date_first_viewed), ')') FROM table;
So for your example: 因此,对于您的示例:
SELECT COUNT(ip_address) as `count`, CONCAT('(', YEAR(date_first_viewed), ', ', MONTH(date_first_viewed), ')') as `date`
FROM `all_website_stats` GROUP BY CONCAT('(', YEAR(date_first_viewed), ', ', MONTH(date_first_viewed), ')')";
should do it! 应该做到的!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.