Sql查询按日期范围拆分

时间:2009-11-12 11:52:32

标签: sql mysql

我想计算一个学生自第一次申请以来按月分开的申请数量。

说我的表结构如下:

Student     ApplicationDate
-------     ---------------
Barry       2009-01-01
Barry       2009-01-20
Barry       2009-01-23
Barry       2009-02-01
Barry       2009-02-15
Barry       2009-03-01

我想要的是:

Student     Month     Applications
-------     -----     ------------
Barry       1/2009    3
Barry       2/2009    2
Barry       3/2009    1

对于所有应用程序,如何在SQL中为所有学生执行此操作?

5 个答案:

答案 0 :(得分:3)

如果我理解正确,可以使用GROUP BY完成:

select 
    student, 
    year(ApplicationDate), 
    month(ApplicationDate), 
    count(*) as Applications
from YourTable
group by student, year(ApplicationDate), month(ApplicationDate)

答案 1 :(得分:3)

为了给你指定的确切输出,我认为这样可行......

select Student,
       DATE_FORMAT(ApplicationDate,'%m/%Y') as 'Month',
       count(*) as 'Applications'
from tableName
group by Student, month(ApplicationDate), year(AppilcationDate)
order by year(ApplicationDate), month(ApplicationDate), Student

编辑:改为使用DATE_FORMAT函数,正如Stanq所建议的那样。

答案 2 :(得分:3)

SELECT 
    student, 
    DATE_FORMAT(ApplicationDate,'%m/%Y') as Month
    count(id) as Applications
from YourTable
group by ApplicationDate

答案 3 :(得分:3)

select 
    student, 
    year(ApplicationDate), 
    month(ApplicationDate), 
    count(*) as Applications
from YourTable
group by student, year(ApplicationDate), month(ApplicationDate)

答案 4 :(得分:0)

select Student, month(ApplicationDate) ApplicationMonth, count(*) 
from table_name 
group by Student, ApplicationMonth
相关问题