سؤال

I have a database table similar to this (but many more entries):

PupilId | PeriodId | Assessment
-------------------------------
1       | 10       | 7
1       | 30       | 7
1       | 50       | 7
2       | 20       | 7
3       | 10       | 7
3       | 20       | 8

I want to find the number of pupils (i.e. distinct PupilId) who got a given assessment at some point up to and including a given PeriodId. Only the most recent assessment before or on the given PeriodId should be used.

For instance:

  • Number of pupils who got 7 on or before PeriodId 100 = 2 (PupilId 1 and 2)
  • Number of pupils who got a 7 on or before PeriodId 10 = 2 (PupilId 1 and 3)
  • Number of pupils who got 8 on or before PeriodId 30 = 1 (PupilId 3)

This is for SQL Azure.

Many thanks.

هل كانت مفيدة؟

المحلول

OK, no answers so here's what I came up with after help from another source:

SELECT COUNT(1)
FROM (
    SELECT PupilId AS pupil_id, Max(PeriodId) AS max_period
    FROM steph1
    WHERE PeriodId <= 100
    GROUP BY PupilId
) steph2, steph1
WHERE
PupilId=pupil_id AND
max_period = PeriodId AND
Assessment = 7

Hope that helps somebody else with the same issue.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top