0

我编写了一个查询,其中涉及创建单个表上保存的总数字和值的百分比(转储到单行)。每个子查询在 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 引入时,只能在选择列表中指定一个表达式。

根据相关子查询,内部查询并没有真正引用外部查询,所以尽管我尽了最大努力,但我不确定如何克服错误。有没有人有什么建议?

4

1 回答 1

0

我们可以用更简单的方式重写您的查询,如下所示。(假设您的表中有一个名为的列genderKS2_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
;
于 2013-10-09T13:56:12.480 回答