Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL中日期字段中的“按年分组”_Mysql_Sql_Date_Group By_Sql Order By - Fatal编程技术网

MySQL中日期字段中的“按年分组”

MySQL中日期字段中的“按年分组”,mysql,sql,date,group-by,sql-order-by,Mysql,Sql,Date,Group By,Sql Order By,我有一个MySQL数据库,它有一个客户表。一些虚拟数据是: customer_id date 000001 2008-10-10 000002 2008-11-11 000003 2010-01-02 000004 2007-04-03 000005 2010-05-05 我想运行一个查询,结果如下: year customer_count 2007 1 2008 2 2010 2

我有一个MySQL数据库,它有一个客户表。一些虚拟数据是:

customer_id    date
000001         2008-10-10
000002         2008-11-11
000003         2010-01-02
000004         2007-04-03
000005         2010-05-05
我想运行一个查询,结果如下:

year    customer_count
2007    1
2008    2
2010    2

我知道我需要使用group by,但是我无法理解如何根据日期字段的年份值进行分组,以及如何将它们按顺序排列。

从日期中提取年份并按日期分组

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

从日期中提取年份并按其分组

select year(date) as year, 
       count(customer_id) as customers
from your_table
group by year
order by year asc
使用函数获取日期的年份部分,并在分组和排序中使用该部分

SELECT YEAR(date) AS year, COUNT(*) AS customer_count
FROM customer
GROUP BY year
ORDER BY year
使用函数获取日期的年份部分,并在分组和排序中使用该部分

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

使用
提取
功能获取日期的相关部分:

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

使用
提取
功能获取日期的相关部分:

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