9

I am receiving this error when trying to execute the query below. Any ideas or suggestions?

Error:

Multiple columns are specified in an aggregated expression containing an outer reference. If an expression being aggregated contains an outer reference, then that outer reference must be the only column referenced in the expression.

SELECT TestInstances.pkTestInstanceID AS 'pkTestInstanceID',
               bands.pkPerformanceLevelReportBandID AS 'BandID',
               bands.StackPosition AS 'StackPosition',
               (SELECT TOP 100 PERCENT SUM(CASE WHEN bands.StackPosition = b.StackPosition THEN 1 ELSE 0 END) * 100/ CASE WHEN COUNT(StudentScores_Subject.pkStudentScoreID) = 0 THEN 1 ELSE COUNT(StudentScores_Subject.pkStudentScoreID) END
                FROM PerformanceLevelReportBands b 
                WHERE b.fkPerformanceLevelReportID = @intPerfLevelReportId
                ORDER BY SUM(CASE WHEN bands.StackPosition = b.StackPosition THEN 1 ELSE 0 END) * 100/ CASE WHEN COUNT(StudentScores_Subject.pkStudentScoreID) = 0 THEN 1 ELSE COUNT(StudentScores_Subject.pkStudentScoreID) END) AS 'Percent',
         COUNT(StudentScores_Subject.pkStudentScoreID) AS 'Count'
         FROM StudentScores_Subject
                INNER JOIN StudentTests ON StudentScores_Subject.fkStudentTestID = StudentTests.pkStudentTestID
                INNER JOIN TestInstances ON  TestInstances.pkTestInstanceID = StudentTests.fkTestInstanceID
                INNER JOIN CAHSEE_TestPeriods ON CAHSEE_TestPeriods.pkTestPeriodID = TestInstances.fkTestPeriodID
                INNER JOIN PerformanceLevelReportBands bands ON bands.fkPerformanceLevelReportID = @intPerfLevelReportId
                LEFT JOIN MMARS_Web_TestInfo_California.dbo.PerfLevelReportBandCutScores cutScores ON cutScores.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
                    AND cutScores.fkGradeID = @intGradeId
                    AND cutScores.fkTestSubjectID IN (SELECT id FROM @tempSubs)
                INNER JOIN PerfLevelReportBandComponents bandComponents ON bandComponents.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID 
                    AND((bandComponents.ScoreValue = StudentScores_Subject.ScoreValue) OR 
                        ((CAST(StudentScores_Subject.ScoreValue AS INT) BETWEEN bandComponents.minScore and bandComponents.maxScore)
                          OR 
                         (CAST(StudentScores_Subject.ScoreValue AS INT) BETWEEN cutScores.minScore and cutScores.maxScore)))
                RIGHT JOIN MM_SchoolYears ON MM_SchoolYears.pkSchoolYearID = TestInstances.fkSchoolYearID
        WHERE MM_SchoolYears.pkSchoolYearID IN (SELECT number FROM itot(@strYearIds, N','))
                AND StudentScores_Subject.fkStudentTestID IN (SELECT id FROM @tempTests)
                AND StudentScores_Subject.fkScoreTypeID = bandComponents.fkScoreTypeID
                AND StudentScores_Subject.fkTest_SubjectID IN (SELECT id FROM @tempSubs)
        GROUP BY TestInstances.pkTestInstanceID, bands.pkPerformanceLevelReportBandID, bands.StackPosition
        ORDER BY TestInstances.pkTestInstanceID, bands.pkPerformanceLevelReportBandID, bands.StackPosition

3 Answers 3

11

The problem is here you can't combine an outer and inner reference in an aggregate function

(SELECT TOP 100 PERCENT SUM(CASE WHEN bands.StackPosition = b.StackPosition THEN 1 ELSE 0 END) * 100/ CASE
                                                                                                             
WHEN COUNT(StudentScores_Subject.pkStudentScoreID) = 0 THEN 1
                                                                                                            
ELSE COUNT(StudentScores_Subject.pkStudentScoreID)
                                                                                                        
 END
   FROM PerformanceLevelReportBands b
   WHERE b.fkPerformanceLevelReportID = @intPerfLevelReportId
   ORDER BY SUM(CASE WHEN bands.StackPosition = b.StackPosition THEN 1 ELSE 0 END) * 100/ CASE
                                                                                              
WHEN COUNT(StudentScores_Subject.pkStudentScoreID) = 0 THEN 1
                                                                                              
ELSE COUNT(StudentScores_Subject.pkStudentScoreID)
                                                                                          
END) AS 'Percent'

So change it to

(SELECT TOP 100 PERCENT SUM(CASE WHEN bb.StackPosition = b.StackPosition THEN 1 ELSE 0 END) * 100/ CASE
                                                                                                            
  WHEN COUNT(StudentScores_Subject.pkStudentScoreID) = 0 THEN 1
                                                                                                            
  ELSE COUNT(StudentScores_Subject.pkStudentScoreID)
                                                                                                        
 END
   FROM PerformanceLevelReportBands b JOIN PerformanceLevelReportBands bb
    ON bb.fkPerformanceLevelReportID =bands.fkPerformanceLevelReportID 
    AND b.fkPerformanceLevelReportID =bb.fkPerformanceLevelReportID
   WHERE b.fkPerformanceLevelReportID = @intPerfLevelReportId
   ORDER BY SUM(CASE WHEN bb.StackPosition = b.StackPosition THEN 1 ELSE 0 END) * 100/ CASE
                                                                                              
 WHEN COUNT(StudentScores_Subject.pkStudentScoreID) = 0 THEN 1
                                                                                              
 ELSE COUNT(StudentScores_Subject.pkStudentScoreID)
                                                                                          
 END) AS 'Percent'

Here is a more thorough explanation.

2
1

I'd recommend commenting out bandComponents then cutScores, rerunning after removing each components and seeing where the query fails. Once you figure out where it's failing, then you can fix it.

Also, could be this line, the query in your Percent column.

ORDER BY SUM(CASE WHEN bands.StackPosition = b.StackPosition THEN 1 ELSE 0 END) * 100 

I tried to organize your query a bit better to make it more legible.

SELECT 
    TestInstances.pkTestInstanceID                      AS 'pkTestInstanceID'
    , bands.pkPerformanceLevelReportBandID              AS 'BandID'
    , bands.StackPosition                               AS 'StackPosition'
    , (
        SELECT TOP 100 PERCENT 
            SUM( CASE 
                    WHEN bands.StackPosition = b.StackPosition 
                    THEN 1 
                    ELSE 0 
                    END) * 100 / 
                CASE 
                    WHEN COUNT(StudentScores_Subject.pkStudentScoreID) = 0 
                    THEN 1 
                    ELSE COUNT(StudentScores_Subject.pkStudentScoreID) 
                    END
            FROM PerformanceLevelReportBands b 
            WHERE b.fkPerformanceLevelReportID = @intPerfLevelReportId
            ORDER BY SUM(CASE WHEN bands.StackPosition = b.StackPosition THEN 1 ELSE 0 END) * 100 
            / 
            CASE 
                WHEN COUNT(StudentScores_Subject.pkStudentScoreID) = 0 
                THEN 1 
                ELSE COUNT(StudentScores_Subject.pkStudentScoreID) 
                END
            )                                           AS 'Percent'
    , COUNT(StudentScores_Subject.pkStudentScoreID)     AS 'Count'
 FROM 
    StudentScores_Subject
INNER JOIN 
    StudentTests ON 
    StudentScores_Subject.fkStudentTestID = StudentTests.pkStudentTestID
INNER JOIN 
    TestInstances ON 
    TestInstances.pkTestInstanceID = StudentTests.fkTestInstanceID
INNER JOIN 
    CAHSEE_TestPeriods ON 
    CAHSEE_TestPeriods.pkTestPeriodID = TestInstances.fkTestPeriodID
INNER JOIN 
    PerformanceLevelReportBands bands ON 
    bands.fkPerformanceLevelReportID = @intPerfLevelReportId
LEFT JOIN 
    MMARS_Web_TestInfo_California.dbo.PerfLevelReportBandCutScores cutScores ON 
        cutScores.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
    AND cutScores.fkGradeID = @intGradeId
    AND cutScores.fkTestSubjectID IN (SELECT id FROM @tempSubs)
INNER JOIN 
    PerfLevelReportBandComponents bandComponents ON 
    bandComponents.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID 
    AND(
        (bandComponents.ScoreValue = StudentScores_Subject.ScoreValue) OR 
        (
            (CAST(StudentScores_Subject.ScoreValue AS INT) BETWEEN bandComponents.minScore and bandComponents.maxScore) OR 
            (CAST(StudentScores_Subject.ScoreValue AS INT) BETWEEN cutScores.minScore and cutScores.maxScore)
         )
        )
RIGHT JOIN 
    MM_SchoolYears ON 
    MM_SchoolYears.pkSchoolYearID = TestInstances.fkSchoolYearID
WHERE 
        MM_SchoolYears.pkSchoolYearID IN (SELECT number FROM itot(@strYearIds, N','))
    AND StudentScores_Subject.fkStudentTestID IN (SELECT id FROM @tempTests)
    AND StudentScores_Subject.fkScoreTypeID = bandComponents.fkScoreTypeID
    AND StudentScores_Subject.fkTest_SubjectID IN (SELECT id FROM @tempSubs)
GROUP BY TestInstances.pkTestInstanceID, bands.pkPerformanceLevelReportBandID, bands.StackPosition
ORDER BY TestInstances.pkTestInstanceID, bands.pkPerformanceLevelReportBandID, bands.StackPosition
2
  • I know for sure that its erring in the nested SELECT with all the aggregations, but I just cannot really think of a way to restructure it so that the outer references are not in the aggregations.
    – frontin
    Commented Oct 23, 2014 at 18:35
  • I see you're joining StudentScores_Subject, but there's no relation defined that links it to PerformanceLevelReportBands.
    – Brent
    Commented Oct 23, 2014 at 18:42
0

I faced the same problem or something similar. I left here both the initial code and the resolution in case it helps you.

Initial code:

SELECT ISNULL((SELECT DateName(mm,DATEADD(mm,Perioada - 1,0))),'Nedefinit') as [Period],MAX(t.TipPerioada) AS TipPerioada,t.Perioada,MAX(t.An) AS An, a.NumePrenume, CAST(t.Volum as float) as ValTip,
            ISNULL((Select Sum(v.Cantitate*p.VolumProdus)
                    From Wme_Vanzari as v 
                    WHERE ('ND'='ND' or v.MarcaAgent = t.MarcaAgent) and  t.[An]=v.AnFactura  and t.Perioada=v.Lunafactura),0) as Realizat,
            '' as Diferenta,'' as DiferentaWD,'' as Procent
            FROM  [Memo_Target] t
            --Aduce Suma de Cantitate si MarcaAgent pentru a nu dubla cu liniile din Vanzari 
            LEFT JOIN (Select SUM(Cantitate) as Cantitate, MarcaAgent 
                        From Wme_Vanzari  
                        WHERE AnFactura = @An 
                        GROUP BY MarcaAgent) v on t.MarcaAgent = v.MarcaAgent
            LEFT JOIN WME_Agenti a on a.Marca = t.MarcaAgent
            --Aduce Suma de VolumProdus, CodProdus si Marca Agent Filtrat dupa Anul dat in parametru, Volum necesar pt a calcula Realizat si a scade din targetul setat
            LEFT JOIN  (SELECT SUM(ISNULL(n.VolumProdus, 0)) AS VolumProdus, v.CodProdus, v.MarcaAgent
                        FROM Wme_NomenclatorProduse n
                        LEFT JOIN Wme_Vanzari v ON v.CodProdus = n.CodIntern
                        WHERE v.MarcaAgent IS NOT NULL AND v.CodProdus IS NOT NULL  AND v.AnFactura = @An
                        GROUP BY v.CodProdus, v.MarcaAgent  ) p ON p.MarcaAgent = t.MarcaAgent
            WHERE (t.Volum IS NOT NULL AND t.Volum > 0)
            AND t.An = @An
            AND (CAST(t.Perioada AS INT) BETWEEN @lunastart AND @lunaend)
            AND TipTarget = @tiptarget
            AND (a.Marca IN (SELECT * FROM dbo.GetIdsTableString(@marcaAgent)) OR @marcaAgent = 'ND')
            GROUP BY a.NumePrenume, t.Volum, Perioada,t.An

Error message was the same, and this is the resolution code:

SELECT ISNULL((SELECT DateName(mm,DATEADD(mm,Perioada - 1,0))),'Nedefinit') as [Period],MAX(t.TipPerioada) AS TipPerioada,t.Perioada,MAX(t.An) AS An, a.NumePrenume, CAST(t.Volum as float) as ValTip,
            (ISNULL((Select Sum(p.VolumProdus)
                    From Wme_Vanzari as v 
                    WHERE ('ND'='ND' or v.MarcaAgent = t.MarcaAgent) and  t.[An]=v.AnFactura  and t.Perioada=v.Lunafactura),0) * sum(v.Cantitate)) as Realizat,
            '' as Diferenta,'' as DiferentaWD,'' as Procent
            FROM  [Memo_Target] t
            --Aduce Suma de Cantitate si MarcaAgent pentru a nu dubla cu liniile din Vanzari 
            LEFT JOIN (Select SUM(Cantitate) as Cantitate, MarcaAgent 
                        From Wme_Vanzari  
                        WHERE AnFactura = @An 
                        GROUP BY MarcaAgent) v on t.MarcaAgent = v.MarcaAgent
            LEFT JOIN WME_Agenti a on a.Marca = t.MarcaAgent
            --Aduce Suma de VolumProdus, CodProdus si Marca Agent Filtrat dupa Anul dat in parametru, Volum necesar pt a calcula Realizat si a scade din targetul setat
            LEFT JOIN  (SELECT SUM(ISNULL(n.VolumProdus, 0)) AS VolumProdus, v.CodProdus, v.MarcaAgent
                        FROM Wme_NomenclatorProduse n
                        LEFT JOIN Wme_Vanzari v ON v.CodProdus = n.CodIntern
                        WHERE v.MarcaAgent IS NOT NULL AND v.CodProdus IS NOT NULL  AND v.AnFactura = @An
                        GROUP BY v.CodProdus, v.MarcaAgent  ) p ON p.MarcaAgent = t.MarcaAgent
            WHERE (t.Volum IS NOT NULL AND t.Volum > 0)
            AND t.An = @An
            AND (CAST(t.Perioada AS INT) BETWEEN @lunastart AND @lunaend)
            AND TipTarget = @tiptarget
            AND (a.Marca IN (SELECT * FROM dbo.GetIdsTableString(@marcaAgent)) OR @marcaAgent = 'ND')
            GROUP BY a.NumePrenume, t.Volum, Perioada,t.An

As you can see, I chose to leave a single column in the first subselect and i was forced to use multiplication operation after this subselect. I hope it helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.