计算在日期范围内积极学习的学生总数

时间:2015-03-05 10:27:11

标签: sql sql-server

我希望得到一个输出,显示每年在用户定义的范围内积极学习的学生总数。

例如DB结构

StudentId     Course       StartDate    EndDate
    1        BSc Maths     2012-01-01   2015-01-01
    2        BSc English   2014-01-01   2017-01-01

如果用户定义在“2013”​​和“2016”之间积极学习,我想得到的输出就是这个;

YEAR  Student_Count
2013        1
2014        2
2015        2
2016        1

感谢您的时间:)

2 个答案:

答案 0 :(得分:0)

你需要有一张年表才能做到这一点。

这里通过Recursive CTE生成年表。您可以创建一个physical年表并使用它而不是递归CTE。

DECLARE @max_yr INT = (SELECT Max(Year(EndDate)) yr FROM   yourtable);

WITH cte
     AS (SELECT Min(Year(StartDate)) yr
         FROM   yourtable
         UNION ALL
         SELECT yr + 1
         FROM   cte
         WHERE  yr < @max_yr)
SELECT a.yr as [YEAR],
       Count(1) as [Student_Count]
FROM   cte a
       JOIN yourtable b
         ON a.yr BETWEEN Year(b.StartDate) AND Year(b.EndDate)
            AND a.yr BETWEEN 2013 AND 2016
GROUP  BY a.yr 

答案 1 :(得分:0)

你可以试试这个,它肯定对我有用 - 显然@startYear和@endYear会被你自己的变量所取代,但我已经把它们留下来让你理解代码是如何工作的:

Create Table #Temp2 ([YEAR] int, Student_Count int)

Declare @startYear int = '2013',
        @endYear int = '2016'

while (@startYear <= @endYear)
Begin
    Insert into #Temp2
    Select @startYear [YEAR], count(studentId)
    from table
    where Cast(Cast(@startYear as varchar) as date) between StartDate and EndDate
    Set @startYear = @startYear + 1
End

Select * from #Temp2