如何对日期字段进行分组以获取MySQL的季度结果?

时间:2011-05-20 04:39:44

标签: mysql date

我有一个工作表,其中包含作业,而leaddate是作业输入的字段。

我想得到的结果是我每个季度的工作数量。我的查询在leaddate字段中计算每个日期的作业。

以下是查询

select count(jobid) as jobcount, leaddate
from jobs
where contactid='19249'
group by leaddate

4 个答案:

答案 0 :(得分:22)

我认为这应该可以胜任:

SELECT YEAR(leaddate) AS year, QUARTER(leaddate) AS quarter, COUNT(jobid) AS jobcount
  FROM jobs
 WHERE contactid = '19249'
 GROUP BY YEAR(leaddate), QUARTER(leaddate)
 ORDER BY YEAR(leaddate), QUARTER(leaddate)

答案 1 :(得分:2)

假设您有一个有效的日期或日期时间字段:

select count(jobid) as jobcount, YEAR(leaddate) yr, QUARTER(leaddate) qt
from jobs
where contactid='19249'
group by yr, qt

答案 2 :(得分:0)

您可以使用Quarter函数从日期开始计算四分之一:

select count(jobid) as jobcount, QUARTER(leaddate) as qt, YEAR(leaddate) as year
from jobs
where contactid='19249'
group by year,qt

答案 3 :(得分:0)

我通常将季度和年份合并到一个YEAR-QUARTER字段中:

select jobid, count(jobid) as jobcount, 
CONCAT( YEAR(leaddate),'-',QUARTER(leaddate) ) as year_qtr
from jobs
where contactid='19249'
group by year_qtr

RETURNS数据如:

19249, 324, 2011-3
19249,   4, 2011-2
19249,  34, 2011-1