TSQL交叉应用计数和总和

时间:2014-02-24 13:13:35

标签: tsql cross-apply

我刚刚发现了CROSS APPLY运算符,并且认为它在操作派生列进行计算时非常有用。

所以,我尝试了以下内容:

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

但是我收到以下错误:

  

APPLY右侧的聚合无法引用列   左侧。

我并不真正理解错误,特别是因为第一个交叉应用实际上是孤立的。我是否完全错了这个概念?

2 个答案:

答案 0 :(得分:5)

交叉应用在线级工作。

“对于左侧的每一行,我们在右侧应用一个函数”。

您的汇总在每行基础上没有意义。

答案 1 :(得分:5)

这些可行。

仅使用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&适用于:

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