开发者

How to list all months that have a requirement in SQL Server?

Let's say I have 3 tables:

开发者_如何学Go
Student (
    student_id, 
    student_type_id, 
    start_date, 
    end_date
) 

RequiredAssignments (
    student_type_id, 
    monthly_assignments_required
)

Assignment (
    student_id, 
    datecompleted
)

Basically, in the RequiredAssignments table, the monthly_assignments_required field is an integer that states how many assignments each student of a given type must turn in each month.

I want to build query that lists a student, a month, how many assignments are required and how many they turned in for every student, for every month between each students given start and end dates.

I'm stuck right now at getting the student_id listed with each month between start and end dates (inclusive)...

Thanks for any help.


You need to create a numbers table.

CREATE TABLE dbo.Numbers
(
n INT PRIMARY KEY
);


WITH E00(N) AS (SELECT 1 UNION ALL SELECT 1),   --2
        E02(N) AS (SELECT 1 FROM E00 a, E00 b), --4
        E04(N) AS (SELECT 1 FROM E02 a, E02 b), --16
        E08(N) AS (SELECT 1 FROM E04 a, E04 b), --256
        E16(N) AS (SELECT 1 FROM E08 a, E08 b)  --65,536
INSERT INTO dbo.Numbers
SELECT TOP 10000 ROW_NUMBER() OVER (ORDER BY (SELECT 0))
FROM E16

Once you have this you can do something like (untested)

SELECT s.student_id,
       DATEADD(MONTH,n-1,start_date) AS MonthStart,
       COUNT(*) 
FROM Student s
JOIN dbo.Numbers ON n <= (1 + DATEDIFF(MONTH,s.start_date, s.end_date)) 
LEFT JOIN Assignment a ON a.student_id = s.student_id and a.datecompleted >= DATEADD(MONTH,n-1,start_date) and a.datecompleted < DATEADD(MONTH,n,start_date)
GROUP BY s.student_id, DATEADD(MONTH,n-1,start_date)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜