Group by year in date field in MySQL

早过忘川 提交于 2019-12-04 05:01:12

问题


I have a MySQL database which has a customer table. Some dummy data is:

customer_id    date
000001         2008-10-10
000002         2008-11-11
000003         2010-01-02
000004         2007-04-03
000005         2010-05-05

I want to run a query which will give me a result like so:

year    customer_count
2007    1
2008    2
2010    2

I know I need to use group by, however I am unable to wrap my head around how to group based on year value of a date field, and how to have them in an order.


回答1:


Extract the year from the date and group by it

select year(date) as year, 
       count(customer_id) as customers
from your_table
group by year
order by year asc



回答2:


Use the EXTRACT function to get the relevant part of the date :

select extract(YEAR from join_d)"Year",count(DISTINCT customer_id) "customer_count" 
from  customer 
group by year
order by year;



回答3:


Use the YEAR function to get the year part of the date, and use that in the grouping and ordering.

SELECT YEAR(date) AS year, COUNT(*) AS customer_count
FROM customer
GROUP BY year
ORDER BY year


来源:https://stackoverflow.com/questions/28023101/group-by-year-in-date-field-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!