假设我有3张桌子:
Student (
student_id,
student_type_id,
start_date,
end_date
)
RequiredAssignments (
student_type_id,
monthly_assignments_required
)
Assignment (
student_id,
datecompleted
)
基本上,在RequiredAssignments
表中,monthly_assignments_required
字段是一个整数,表示每个学生每个月必须转入的分配数。
我想建立一个查询,列出一个学生,一个月,需要多少作业,以及每个学生为每个学生上交多少,每个学生每个月给出开始和结束日期。
我现在被困在每个月的student_id
列出的开始日期和结束日期(含)之间......
感谢您的帮助。
答案 0 :(得分:2)
您需要创建一个数字表。
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
一旦你有了这个,你可以做一些像(未经测试的)
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)