MySQL 按 Unix 时间戳字段的月份分组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9698977/
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 12:31:10  来源:igfitidea点击:

group by month of unix timestamp field

mysqlselectcountunix-timestamp

提问by scarhand

I'm trying to get my code to output in the following format:

我试图让我的代码以以下格式输出:

january 2012 - 34
february 2012 - 23

where 34 and 23 would be a count of the total rows that fall within that month that have the id_dealership of 7. I need this to output all data for every month that an assignment was ever made.

其中 34 和 23 将是该月内 id_dealership 为 7 的总行数。我需要它来输出每个月的所有数据。

The assignmentstable structure is as follows:

assignments表结构如下:

id_dealer (int)
date_assigned (int)

I've tried this but it does not work at all:

我试过这个,但它根本不起作用:

SELECT MONTH(date_assigned), YEAR(date_assigned), COUNT(*)
FROM assignments
GROUP BY MONTH(date_assigned), YEAR(date_assigned)

回答by Eugen Rieck

SELECT 
  MONTH(FROM_UNIXTIME(date_assigned)), 
  YEAR(FROM_UNIXTIME(date_assigned)), 
  COUNT(*)
FROM assignments
GROUP BY 
  MONTH(FROM_UNIXTIME(date_assigned)), 
  YEAR(FROM_UNIXTIME(date_assigned))

回答by giorashc

Your date_assigned column should be of type DATE. AFAIK MONTH works on date columns and if you want the month name from a DATE column use : MONTHNAME(date_assigned)

您的 date_assigned 列的类型应为 DATE。AFAIK MONTH 适用于日期列,如果您想要 DATE 列中的月份名称,请使用:MONTHNAME(date_assigned)

回答by Sergeev Alexey

try this query

试试这个查询

SELECT 
  MONTH(FROM_UNIXTIME(date_assigned)), 
  YEAR(FROM_UNIXTIME(date_assigned)), 
  COUNT(*)
FROM assignments
GROUP BY 1,2