Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I group a date field to get quarterly results in MySQL?

Tags:

I have a job table that holds jobs and leaddate is the field for the job entry.

The result I want to get is the number of jobs I have in each quarter. My query counts jobs of each date in the leaddate field.

Here is the query

select count(jobid) as jobcount, leaddate
from jobs
where contactid='19249'
group by leaddate
like image 216
abnab Avatar asked May 20 '11 04:05

abnab


People also ask

How do I get quarterly date in SQL?

In SQL Server, you can use DATEPART(QUARTER,whn) and YEAR(whn) . In Oracle, you can use TO_CHAR(whn,'Q') and TO_CHAR(whn,'YYYY') for the quarter and year.

How do I group data in MySQL?

The MySQL GROUP BY Statement The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country". The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

How do I select a specific date in MySQL?

You can use DATE() from MySQL to select records with a particular date. The syntax is as follows. SELECT *from yourTableName WHERE DATE(yourDateColumnName)='anyDate'; To understand the above syntax, let us first create a table.

How can I get records between two dates in MySQL?

Use the DATEDIFF() function to retrieve the number of days between two dates in a MySQL database.


2 Answers

I think this should do the job:

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)
like image 138
Jonathan Leffler Avatar answered Oct 16 '22 15:10

Jonathan Leffler


Supposing you have a valid date or datetime field:

select count(jobid) as jobcount, YEAR(leaddate) yr, QUARTER(leaddate) qt
from jobs
where contactid='19249'
group by yr, qt
like image 24
zerkms Avatar answered Oct 16 '22 16:10

zerkms