我正在尝试使用以下查询计算两列:
select distinct [District],
count (Distinct [Student Identifier Statewide California])
as '11-12 Enrollment',
(select count (Distinct IncdtKey)
From [dbo].[DisciplineStudentFile1112]
where GrdLvLKey in ('15', '01', '02', '03', '04',
'05', '06', '07', '08', '09',
'10', '11', '12', '18', '19')) as Total_Incidents
From
dbo.SSID1112StudentEnrollmentRecords with (nolock)
inner join
[dbo].[SchoolDetail] on CDSCode = dbo.SSID1112StudentEnrollmentRecords.CDSOrig
where
[EnrollStatCodeOrig] like '10'
and
[Grade Level Code] in ('PS', 'KN', '01', '02', '03',
'04', '05', '06', '07', '08',
'09', '10', '11', '12', 'UE', 'US')
group by [District]
order by [District]
我的结果是:
District 11-12 Enrollment Total_Incidents
AB Unified 20662 896371
CE Unified 5387 896371
DR Unified 526 896371
FJ Unified 1506 896371
KT Unified 8415 896371
我无法弄清楚如何获取Total_Incidents
列中的个别计数而不是总计896371计数?
答案 0 :(得分:0)
一种简单的方法是将子查询与外部查询相关联:
select distinct SD.District,
count ( distinct SER.[Student Identifier Statewide California] ) as [11-12 Enrollment],
( select count( distinct DSF.IncdtKey ) from dbo.DisciplineStudentFile1112 as DSF
where DSF.GrdLvLKey in ( '15', '01', '02', '03', '04', '05', '06', '07', '08', '09',
'10', '11', '12', '18', '19' ) and -- Note additional condition here.
DSF.District = SD.District ) as Total_Incidents
from dbo.SSID1112StudentEnrollmentRecords as SER with (nolock) inner join
dbo.SchoolDetail as SD on SD.CDSCode = SER.CDSOrig
where SER.EnrollStatCodeOrig like '10' and
[Grade Level Code] in ( 'PS', 'KN', '01', '02', '03', '04', '05', '06', '07', '08',
'09', '10', '11', '12', 'UE', 'US' )
group by SD.District
order by SD.District
我对表模式做了一些假设。我建议在使用连接时为每个表提供别名,并在每个引用上使用别名以避免混淆。
另一种解决方案是使用DisciplineStudentFile1112
的其他联接,然后使用GROUP BY
汇总结果。