Question

I've just discovered The CROSS APPLY operator and was under the impression it was very useful in manipulating derived columns for calculations.

So, I tried the following:

SELECT leadYear,TotalLeadsCalled,SuccessLeadsCalled,SuccessLeadsPercent
FROM dbo.tblBinOutboundCallActivity 
CROSS APPLY(VALUES (YEAR(leadactivitydate))) AS a1(leadyear) 
CROSS APPLY(VALUES (COUNT(leadStatusID))) AS a2(TotalLeadsCalled) 
CROSS APPLY(VALUES (COUNT(CASE WHEN leadStatusID = 2 THEN 1 ELSE NULL END))) AS a3(SuccessLeadsCalled) 
CROSS APPLY(VALUES (SUM((SuccessLeadsCalled/TotalLeadsCalled)*100))) AS a4(SuccessLeadsPercent) 
GROUP BY leadYear

But I get the following error:

Aggregates on the right side of an APPLY cannot reference columns from the left side.

I don't really understand the error, especially as the first cross apply actually works in isolation. Have I just got the concept completely wrong?

Was it helpful?

Solution

Cross apply works at line level.

"For each line on the left, we apply a function on the right".

Your aggregation has no meaning on per line bases.

OTHER TIPS

These would work.

Only using APPLY:

SELECT leadYear,TotalLeadsCalled,SuccessLeadsCalled,SuccessLeadsPercent
FROM dbo.tblBinOutboundCallActivity a
    CROSS APPLY (SELECT YEAR(leadactivitydate) leadyear FROM dbo.tblBinOutboundCallActivity WHERE YEAR(leadactivitydate) = YEAR(a.leadactivitydate)) a1
    CROSS APPLY (SELECT COUNT(leadStatusID) TotalLeadsCalled FROM dbo.tblBinOutboundCallActivity WHERE YEAR(leadactivitydate) = a1.leadyear) a2
    CROSS APPLY (SELECT COUNT(CASE WHEN leadStatusID = 2 THEN 1 ELSE NULL END) SuccessLeadsCalled FROM dbo.tblBinOutboundCallActivity WHERE YEAR(leadactivitydate) = a1.leadyear) a3
    CROSS APPLY (SELECT 100.*SuccessLeadsCalled/TotalLeadsCalled SuccessLeadsPercent) a4
GROUP BY leadYear,TotalLeadsCalled,SuccessLeadsCalled,SuccessLeadsPercent

CTE & APPLY:

WITH Years AS
(
    SELECT YEAR(leadactivitydate) leadyear
    FROM dbo.tblBinOutboundCallActivity
    GROUP BY YEAR(leadactivitydate)
)
    SELECT leadYear,TotalLeadsCalled,SuccessLeadsCalled,SuccessLeadsPercent
    FROM Years      
        CROSS APPLY (SELECT COUNT(leadStatusID) TotalLeadsCalled FROM dbo.tblBinOutboundCallActivity WHERE YEAR(leadactivitydate) = leadyear) a2
        CROSS APPLY (SELECT COUNT(CASE WHEN leadStatusID = 2 THEN 1 ELSE NULL END) SuccessLeadsCalled FROM dbo.tblBinOutboundCallActivity WHERE YEAR(leadactivitydate) = leadyear) a3
        CROSS APPLY (SELECT 100.*SuccessLeadsCalled/TotalLeadsCalled SuccessLeadsPercent) a4
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top