我编写了一个查询,其中涉及在单个表上创建总和数字和值的百分比(转储到单行)。每个子查询关于WHERE参数略有不同。例如:
select distinct
count(KS2_PupilMatchingRefAnonymous) AS 'Total Pupils',
(select count(KS2_PupilMatchingRefAnonymous)
from KS2_CandInd_2011
where KS2_MMSCH=1
and KS2_ELIGENGTA=1) AS 'All Eligible Pupils',
(select count(*)
from KS2_CandInd_2011
where KS2_MMSCH=1
and KS2_ELIGENGTA=1
and KS2_ELIGENGTA=1
and FSMeligible=1) AS 'Eligible FSM only',
(select round(
(cast((
select count(*)
from KS2_CandInd_2011
where KS2_MMSCH=1
and KS2_ELIGENGTA=1
and KS2_ELIGENGTA=1
and FSMeligible=1) AS float) /
cast((
select count(KS2_PupilMatchingRefAnonymous)
from KS2_CandInd_2011
where KS2_MMSCH=1
and KS2_ELIGENGTA=1) AS float))*100,2
)) AS '% Eligible FSM'
from KS2_CandInd_2011
where KS2_MMSCH=1
我现在想要根据性别将每个子查询细分为COUNT(当然还有GROUP BY)。如果性别的COUNT / GROUP BY放在外部查询中,我只会得到“总学生”值的细分/拆分。
如果我尝试在子查询中输入相同的子句,我被告知
Msg 116,Level 16,State 1,Line 12 当未使用EXISTS引入子查询时,只能在选择列表中指定一个表达式。
根据相关的子查询,内部查询并不真正引用外部查询,因此即使我最好的尝试,我也不确定如何克服错误。有没有人有任何建议?
答案 0 :(得分:0)
我们可以用更简单的方式重新编写您的查询,如下所示。(假设您的表中有一个名为gender
的列:KS2_CandInd_2011
select
a.gender
,count(*) AS 'Total Pupils',
,sum(case
when KS2_MMSCH=1 and KS2_ELIGENGTA=1 then 1
else 0
end
) as 'All Eligible Pupils'
,sum(case
when KS2_MMSCH=1 and KS2_ELIGENGTA=1 and KS2_ELIGENGTA=1 and FSMeligible=1 then 1
else 0
end) as 'Eligible FSM only'
,round(cast( sum(case
when KS2_MMSCH=1 and KS2_ELIGENGTA=1 then 1
else 0
end
) as float)/
cast(sum(case
when KS2_MMSCH=1 and KS2_ELIGENGTA=1 and KS2_ELIGENGTA=1 and FSMeligible=1 then 1
else 0
end) as float)
*100,2) AS '% Eligible FSM'
from KS2_CandInd_2011 as a
where a.KS2_MMSCH=1
group by a.gender
order by a.gender;
以下是我相信会为您提供原始查询的确切输出:
select
,count(*) AS 'Total Pupils',
,sum(case
when KS2_MMSCH=1 and KS2_ELIGENGTA=1 then 1
else 0
end
) as 'All Eligible Pupils'
,sum(case
when KS2_MMSCH=1 and KS2_ELIGENGTA=1 and KS2_ELIGENGTA=1 and FSMeligible=1 then 1
else 0
end) as 'Eligible FSM only'
,round(cast( sum(case
when KS2_MMSCH=1 and KS2_ELIGENGTA=1 then 1
else 0
end
) as float)/
cast(sum(case
when KS2_MMSCH=1 and KS2_ELIGENGTA=1 and KS2_ELIGENGTA=1 and FSMeligible=1 then 1
else 0
end) as float)
*100,2) AS '% Eligible FSM'
from KS2_CandInd_2011 as a
where a.KS2_MMSCH=1
;