Надеюсь, это поможет.
With t1 as (
Select leaving, admission, enrolment,
(case when year = '7' then 1 else 0 end) as Y7,
(case when year = '8' then 1 else 0 end) as Y8,
(case when year = '9' then 1 else 0 end) as Y9,
(case when year = '10' then 1 else 0 end) as Y10,
(case when year = '11' then 1 else 0 end) as Y11
From totals),
t2 as (
Select 1 as [Student Group], Y7, Y8, Y9, Y10, Y11
From t1
Where leaving is null and admission <= GETDATE() and enrolment in ('single registration','main - dual registration')
Union all
Select 2, Y7, Y8, Y9, Y10, Y11
From t1
Where admission > @RefDate and enrolment in ('single registration','main - dual registration')
Union all
Select 3, Y7, Y8, Y9, Y10, Y11
From t1
Where leaving > @RefDate and enrolment in ('single registration','main - dual registration'))
/* Select result */
Select case when [Student Group] = 1
then 'On Roll'
else case when [Student Group] = 2
then 'New'
else 'Leaving'
end
end as [Student Group Name],
sum(Y7) as [Y7 No.], 1.0 * sum(Y7) / count(1) as [Y7 %],
sum(Y8) as [Y8 No.], 1.0 * sum(Y8) / count(1) as [Y8 %],
sum(Y9) as [Y9 No.], 1.0 * sum(Y9) / count(1) as [Y9 %],
sum(Y10) as [Y10 No.], 1.0 * sum(Y10) / count(1) as [Y10 %],
sum(Y11) as [Y11 No.], 1.0 * sum(Y11) / count(1) as [Y11 %]
From t2
Group by [Student Group]
--Order by [Student Group]
Или
/* Select result */
Select StudentGroup.[Student Group Name],
t3.[Y7 No.], t3.[Y7 %],
t3.[Y8 No.], t3.[Y8 %],
t3.[Y9 No.], t3.[Y9 %],
t3.[Y10 No.], t3.[Y10 %],
t3.[Y11 No.], t3.[Y11 %]
From (
Select [Student Group],
sum(Y7) as [Y7 No.], 1.0 * sum(Y7) / count(1) as [Y7 %],
sum(Y8) as [Y8 No.], 1.0 * sum(Y8) / count(1) as [Y8 %],
sum(Y9) as [Y9 No.], 1.0 * sum(Y9) / count(1) as [Y9 %],
sum(Y10) as [Y10 No.], 1.0 * sum(Y10) / count(1) as [Y10 %],
sum(Y11) as [Y11 No.], 1.0 * sum(Y11) / count(1) as [Y11 %]
From t2
Group by [Student Group]
) t3
Inner join (
Select 1 as [Student Group], 'On Roll' as [Student Group Name]
Union
Select 2, 'New'
Union
Select 3, 'Leaving'
) StudentGroup
On t3.[Student Group] = StudentGroup.[Student Group]
Order by t3.[Student Group]
Приветствия!